# Tietokoneharjoitus 7

## Tehtävä 5

```file<-"http://cc.oulu.fi/~jklemela/stafin/sp500-ndx100.txt"
sp500<-data[,1]
ndx100<-data[,2]

pituus<-length(sp500)
r.sp500<-sp500[2:pituus]/sp500[1:(pituus-1)]
plot(r.sp500,type="l")

r.ndx100<-ndx100[2:pituus]/ndx100[1:(pituus-1)]
plot(r.ndx100,type="l")

# (a)i. SP 500

mu<-mean(r.sp500)
mur<-1
sigma<-sd(r.sp500)

gammat<-seq(1,10,0.1)
b1<-(mu-mur)/sigma^2*1/gammat

plot(gammat,b1)

# (a)ii. Nasdaq-100

mu<-mean(r.ndx100)
mur<-1
sigma<-sd(r.ndx100)

gammat<-seq(1,10,0.1)
b2<-(mu-mur)/sigma^2*1/gammat
plot(gammat,b2)

# molemmat

matplot(gammat,b1)

# (b) SP500 ja Nasdaq-100  ################################

mu1<-mean(r.sp500)
mu2<-mean(r.ndx100)
sigma12<-cov(r.sp500,r.ndx100)
sigma1<-sd(r.sp500)
sigma2<-sd(r.ndx100)

gammat<-seq(1,10,0.1)
b<-(mu2-mu1-gammat*(sigma12-sigma1^2))/(sigma1^2+sigma2^2-2*sigma12)/gammat

plot(gammat,b)

# (c) Backtesting ######################################

gamma<-5
alku<-1000
r.oma<-matrix(0,length(r.ndx100)-alku,1)
for (i in alku:(length(r.ndx100)-1)){
cur.sp500<-r.sp500[1:i]
cur.ndx100<-r.ndx100[1:i]

mu1<-mean(cur.sp500,na.rm=TRUE)
mu2<-mean(cur.ndx100,na.rm=TRUE)
sigma12<-cov(cur.sp500,cur.ndx100,use="na.or.complete")
sigma1<-sd(cur.sp500,na.rm=TRUE)
sigma2<-sd(cur.ndx100,na.rm=TRUE)

b<-(mu2-mu1-gamma*(sigma12-sigma1^2))/(sigma1^2+sigma2^2-2*sigma12)/gamma
r.oma[i-alku+1]<-(1-b)*r.sp500[i+1]+b*r.ndx100[i+1]
}
plot(r.oma,type="l")

sqrt(250)*mean(r.oma-1)/sd(r.oma)
250*mean(r.oma-1)
sqrt(250)*sd(r.oma)

#[1] 0.5326991
#[1] 0.1172191
#[1] 0.2200475

wealth<-matrix(0,length(r.oma)+1,1)
wealth[1]<-1
for (i in 1:length(r.oma)) wealth[i+1]<-wealth[i]*r.oma[i]
plot(wealth,type="l")

wealth.nasdaq<-matrix(1,length(r.oma)+1,1)
wealth.sp500<-matrix(1,length(r.oma)+1,1)
for (i in (alku+1):length(r.ndx100)){
wealth.nasdaq[i-alku+1]<-wealth.nasdaq[i-alku]*r.ndx100[i]
wealth.sp500[i-alku+1]<-wealth.sp500[i-alku]*r.sp500[i]
}
matplot(wealth.nasdaq,type="l",col="blue")