
install.packages("readxl")
install.packages('Rcpp')
install.packages('POET')
install.packages("writexl")
library(Rcpp)
library(readxl)
library(POET)
library(writexl)

ff=read_excel("Portfolio_ret.xlsx", sheet = "Anomaly",range = "A2:BS518")
f0=ff[ff$ym>=197401&ff$ym<=201612,]     
f1=f0[,2:71]

ones=rep(1,nrow(f1))
f2=f1-ones%*%t(colMeans(f1))

Z=data.matrix(f2,rownames.force = NA)
Z=cbind(ones,Z)

K=1
S2<-POET(t(Z),K,.5,'soft','vad')$SigmaY
S2 = data.frame(S2)
write_xlsx(S2, "S2_1.xlsx")

K=3
S2<-POET(t(Z),K,.5,'soft','vad')$SigmaY
S2 = data.frame(S2)
write_xlsx(S2, "S2_3.xlsx")


K=5
S2<-POET(t(Z),K,.5,'soft','vad')$SigmaY
S2 = data.frame(S2)
write_xlsx(S2, "S2_5.xlsx")

K=6
S2<-POET(t(Z),K,.5,'soft','vad')$SigmaY
S2 = data.frame(S2)
write_xlsx(S2, "S2_6.xlsx")