我正在尝试在R中实现动量交易策略,并尝试了以下代码作为第一步。 形成期从t = -12到t = -2 从t = 0到t = 2的保持时间(3个周期) 认为可以简化很多事情,但是由于我是R的新手,所以这是我的第一次尝试。 如果有人认为以下代码“可以”(当然,必须先进行数据修改),是否有一种方法可以针对每个t自动运行该代码?现在我必须手动调整周期。
library(GetBatchSymbols)
library(quantmod)
library(dplyr)
#Getting Tickers
df.SP<-GetSP500Stocks()
#Getting Stockdata
data1<-BatchGetSymbols(tickers = df.SP$company,first.date = "2010- 01-01",last.date = "2015-01-01",freq.data = "monthly",do.complete.data = TRUE)
#extract return data
mat<-matrix(data = data2$df.tickers$ret.adjusted.prices,nrow = 60,byrow = FALSE)
mat<-as.data.frame(mat)
#extract ticker data
mat2<-matrix(data2$df.tickers$ticker, nrow =60 , ncol = 459)
#create ticker vector
mat2<-mat2[1,]
#implement names in mat
names(mat)<-paste(c(mat2))
#adding 1 to get rate of change
mat2<-mat+1
#extracting date (60 since 5 yr data)
date<-data2$df.tickers$ref.date
date<-as.data.frame(date)
date<-date[1:60,]
date<-as.Date(date,format("%Y-%m-%d"))
#combine date with mat2
mat2<-cbind.data.frame(date,mat2)
#add line of 1 as a starting point
mat2[1,2:459]<-1
#extract holding period data in mat3
mat3<-mat2[12:14,]
#create function to apply cumprod
cum.prod<-function(x) cumprod(x)
#apply cumprod on formation period (t-12 until t-2 (skip t-1 because of short term reversal))
matfirst<-apply(mat2[1:10,], 2,function(x) {cum.prod(c(x))})
#sort Returns from formation period
A<-sort(matfirst[10,])
A<-as.data.frame(A)
#extract rownames
N<-rownames(A)
N<-as.data.frame(N)
#lowest 50 stocks names
L<-N[1:50,]
L<-as.character(L)
#select returns by lowest 50 stock names in holding period table
firsttryL<-select(mat3,one_of(L))
#apply cumprod to holding period table
Lret<-apply(firsttryL, 2,function(x) {cum.prod(c(x))})
#get mean return in last row
Lret1<-mean(Lret[3,])
#get percentage return in holding period
Lret1<-Lret1-1
#same as above
W<-(N[409:458,])
W<-as.character(W)
firsttryW<-select(mat3,one_of(W))
Wret<-apply(firsttryW, 2,function(x) {cum.prod(c(x))})
Wret1<-mean(Wret[3,])
Wret1<-Wret1-1
#Momentum factor
WML<-Wret1-Lret1