Sei sulla pagina 1di 2

6/18/12 6:19 PM

R comamnds used in Lecture 7


> da=read.table("m-gmsp6708.txt",header=T) % Load GM and SP monthly returns.
> gm=log(da[,2]+1) % compute log returns
> sp=log(da[,3]+1)
> m1=lm(gm~sp) % Fit the Market Model
> summary(m1)
> length(sp) % find out the number of observations
[1] 502
> x1=rep(1,502) % create an indicator to non-positive SP log returns.
> for (i in 1:502){
+ if(sp[i]>0)x1[i]=0
+ }
> x2=x1*sp % create cross-product variable (Slope)
> m2=lm(gm~sp+x1) % Fit all possible models.
> summary(m2)
> m3=lm(gm~sp+x2)
> summary(m3)
> m4=lm(gm~sp+x1+x2)
> summary(m4)
>
> library(nnet) % Load neural networks package
> da=read.table("m-ibmln2699.txt") %%% Monthly IBM log returns
> dim(da)
[1] 888 1
> x=da[,1]
> y=x[4:864]
> ibm.x=cbind(x[3:863],x[2:862],x[1:861])
> ibm.nn=nnet(ibm.x,y,size=2,linout=T,skip=T,maxit=10000)
# weights: 14
initial value 57144.980603
iter 10 value 37416.808037 %%% If you like to skip the output here,
iter 20 value 37068.765174 %%% you can use subcommand "trace=FALSE".
iter 30 value 36704.284456
iter 40 value 36633.209122
iter 50 value 36596.942932
iter 60 value 36514.599641
iter 70 value 36491.019871
final value 36491.015022
converged
> summary(ibm.nn)
a 3-2-1 network with 14 weights
options were - skip-layer connections linear output units
b->h1 i1->h1 i2->h1 i3->h1 # Coefficients for the h1 (First node of Hidden layer)
-368.93 568.82 -295.27 -885.04
b->h2 i1->h2 i2->h2 i3->h2 # coefficients for the h2.
91.71 40.63 -181.32 -218.14
b->o h1->o h2->o i1->o i2->o i3->o # Coefficients for output node.
1.01 -3.17 3.25 0.16 0.07 -0.03
> sse=sum((y-predict(ibm.nn,ibm.x)^2)) # Compute sum of squares of residuals.
> sse
[1] -1483.777
> ibm.p=cbind(x[864:887],x[863:886],x[862:885])
> yh=predict(ibm.nn,ibm.p) # Prediction
> yo=x[865:888]
> ssfe=sum((yo-yh)^2) # Compute sum of squares of forecast errors.
> ssfe

http://faculty.chicagobooth.edu/ruey.tsay/teaching/bs41202/sp2010/Rcommands_lec7.txt Page 1 of 2
6/18/12 6:19 PM

[1] 2125.665
>
**** You can run the backtest using neural networks ("backnnet")
> source("backnnet.R")
> m1=backnnet(ibm.x,y,840) # here 840 is the starting forecast origin.

*** You can use the program "hfrtn.R" to compute intraday log returns.
> source("hfrtn.R")
> m1=hfrtn(da,5) # here da: the trade-by-trade data
# 5 means 5-minute returns. (Interval is in minutes.)

http://faculty.chicagobooth.edu/ruey.tsay/teaching/bs41202/sp2010/Rcommands_lec7.txt Page 2 of 2

Potrebbero piacerti anche