Tietokoneharjoitus 9

SP500 osakeindeksin hintatiedot ovat csv-muodossa osoitteessa

http://cc.oulu.fi/~jklemela/stainf/sp500.csv

Lue data R:aan ja muuta hintojen aikasarja tuottojen aikasarjaksi.

file<-"http://cc.oulu.fi/~jklemela/stainf/sp500.csv"
data<-read.csv(file=file)
sp500<-data[,7]
sp500<-sp500[length(sp500):1]
plot(sp500,type="l")

pituus<-length(sp500)
tuotto<-log(sp500[2:pituus])-log(sp500[1:(pituus-1)])
plot(tuotto,type="l")

Tehtävä 5(a)

Estimoidaan tuottojen odotusarvo numeerisesti suurimman uskottavuuden menetelmalla.

n<-length(tuotto)
sigma<-sd(tuotto)
negloglik.gauss<-function(mu)
{
  loglik<-n*log(1/sigma)-sum((tuotto-mu)^2/sigma^2)/2
  return(-loglik)
}

par<-0
lower<--0.1
upper<-0.1
#method<-"Nelder-Mead"
method<-"L-BFGS-B"
#"BFGS"
#method<-"CG"
#"SANN"
su.gauss<-optim(par,negloglik.gauss,method=method,lower=lower,upper=upper)
su.gauss
250*su.gauss$par

[1] 0.07047155

250*mean(tuotto)
sqrt(250)*sd(tuotto)

[1] 0.07047155
[1] 0.1549468

Tehtävä 5(b)

Estimoidaan tuottojen odotusarvo ja keskihajonta numeerisesti suurimman uskottavuuden menetelmalla.

n<-length(tuotto)
negloglik.gauss<-function(theta)
{
  loglik<-n*log(1/theta[2])-sum((tuotto-theta[1])^2/theta[2]^2)/2
  return(-loglik)
}

par<-c(0,0.005)
lower<-c(-0.1,0.00001)
upper<-c(0.1,0.1)
#method<-"Nelder-Mead"
method<-"L-BFGS-B"
#"BFGS"
#method<-"CG"
#"SANN"
su.gauss<-optim(par,negloglik.gauss,method=method,lower=lower,upper=upper)
su.gauss
su.gauss$par

250*su.gauss$par[1]
sqrt(250)*su.gauss$par[2]

#[1] 0.06993676
#[1] 0.1561824

250*mean(tuotto)
sqrt(250)*sd(tuotto)

#[1] 0.07047155
#[1] 0.1549468


u<--q
negloglik.pareto<-function(b)
{
  summa<-0
  for (i in 1:n) summa<-summa+log(b*u^b*left.tail[i]^(-b-1))
  return(-summa)
}

par<-2
lower<-1
upper<-5
method<-"L-BFGS-B"
su.pareto<-optim(par,negloglik.pareto,method=method,lower=lower,upper=upper)
su.pareto

n<-length(tuotto) negloglik.gauss<-function(theta) { summa<-0 for (i in 1:n) summa<-summa+log(1/theta[2])-(tuotto[i]-theta[1])^2/theta[2]^2/2 return(-summa) }