forked from Mingqipei/spltteam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
4-prepare for iteration.R
81 lines (56 loc) · 1.41 KB
/
4-prepare for iteration.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#get the initial value of beta
datamatrix=cbind(DBframe$index,DBframe$PE,DBframe$turnover,DBframe$csv)
colnames(datamatrix)=c("index","PE","turnover","csv")
Y=DBframe$Y
result=lm(formula = Y ~ datamatrix)
summary(result)
#test heteroscedasticity
par(mfrow=c(2,2)) # init 4 charts in 1 panel
plot(result)
library("lmtest")
restest=bptest(result)
#get the initial beta
beta0=result$coefficients
#estimate alpha in ARCH
res = result$resid
res2=res^2
res=as.matrix(res2)
m=length(res)
U=res[4:m]
v1=matrix(res[3:(m-1)],nrow=m-3)
v2=matrix(res[2:(m-2)],nrow=m-3)
v3=matrix(res[1:(m-3)],nrow=m-3)
V=cbind(v1,v2,v3)
lm2=lm(U~V)
summary(lm2)
alphat=lm2$coefficients
#calculate sigma
v4=matrix(rep(1,m-3),nrow=m-3)
Vt=cbind(v4,v1,v2,v3)
sigma=Vt%*%alphat
#calculate omega
et=result$resid
et=as.vector(et)
et2=matrix(0,nrow=3896)
mode(et2)
et2[which(et<0)]=1
et2[which(et==0)]=1
et2[which(et>0)]=0
et2=as.vector(et2)
thetavec=rep(theta,3896)
thetavec=as.vector(thetavec)
omega=abs(thetavec-et2)
is.vector(omega)
omega=omega[4:3896]
#calculate the new beta
Xt=cbind(1,datamatrix[4:3896,])
j=1
xxsummatrix=matrix(0,nrow=5,ncol = 5)
xysummatrix=matrix(0,nrow = 5,ncol = 1)
ynew=Y[4:3896]
for (j in 1:3893) {
xxsummatrix=xxsummatrix+omega[j]/sigma[j]*crossprod(t(Xt[j,]),Xt[j,])
xysummatrix=xysummatrix+omega[j]/sigma[j]*crossprod(t(Xt[j,]),ynew[j])
}
solve(xxsummatrix)
beta1=crossprod(t(solve(xxsummatrix)),xysummatrix)