原创R语言TMA三均线策略实现附代码数据.docx
《原创R语言TMA三均线策略实现附代码数据.docx》由会员分享,可在线阅读,更多相关《原创R语言TMA三均线策略实现附代码数据.docx(36页珍藏版)》请在冰豆网上搜索。
source('in-sample_period.R')library(TTR)
getOrders<-function(store,newRowList,currentPos,params){allzero <-rep(0,length(newRowList))#usedforinitializingvectors
################################################
#Youdonotneedtoeditthispartofthecode#thatinitializesandupdatesthestore
################################################
if(is.null(store))
store<-initStore(newRowList)else
store<-updateStore(store,newRowList)################################################
pos<-allzero################################################
#Thisnextcodesectionistheonlyoneyou#needtoeditforgetOrders
#
#Theifconditionisalreadycorrect:
#youshouldonlystartcomputingthemoving
#averageswhenyouhaveenoughcloseprices#forthelongmovingaverage
################################################
if(store$iter>params$lookbacks$long){
for(indexin 1:
length(params$series)){current_close= last(store$cl[[index]])close=store$cl[[index]]
xtsclose= as.xts(close)
GETtma= getTMA(xtsclose,params$lookbacks)
pos= getPosSignFromTMA(GETtma)*getPosSize(current_close)
}
}################################################
#Youdonotneedtoeditthispartofthecode#thatinitializesandupdatesthestore
################################################
marketOrders<--currentPos+pos
return(list(store=store,marketOrders=marketOrders,limitOrders1=allzero,limitPrices1=allzero,limitOrders2=allzero,limitPrices2=allzero))
}
########################################################################
#Thefollowingfunctionshouldbeeditedtocompletesteps1to3#ofcomp22assignment2
getTMA<-function(close_prices,lookbacks){
if(!
("long" %in% names(lookbacks)&&"short" %in% names(lookbacks)&&"medium" %in% names(lookbacks)))
stop("E01:
Atleastoneof\"short\",\"medium\",\"long\"ismissingfromnames(lookbacks)")
#ReplaceTRUEto
#checkthattheelementsoflookbacksareallintegers
if(!
(class(lookbacks[[1]])=="integer"&&class(lookbacks[[2]])=="integer"&&class(lookbacks[[3]])=="integer"))
stop("E02:
Atleastoneofthelookbacksisnotanintegeraccordingtois.integer()")
#ReplaceTRUEto
#checkthatlookbacks$shortif(!
(lookbacks[[1]]stop("E03:
Thelookbacksdonotsatisfylookbacks$shortium#ReplaceTRUEto
#checkthatclose_pricesisanxts
if(!
(class(close_prices)[1]=="xts"))
stop("E04:
close_pricesisnotanxtsaccordingtois.xts())"
#ReplaceTRUEto
#checkthatclose_priceshasenoughrows
if(nrow(close_prices)stop("E05:
close_pricesdoesnotenoughrows)"
#ReplaceTRUEto
#checkthatclose_pricescontainsacolumncalled"Close"
if(!
(colnames(close_prices)=="Close"))
stop("E06:
close_pricesdoesnotcontainacolumn\"Close\")"
sma=numeric(0)for(iin1:
3){
sma[i]<-as.numeric(last(SMA(close_prices,n=lookbacks[[i]])))#TTRversion#converttovectorfromxts
}
smalist<-list(short=sma[1],medium=sma[2],long=sma[3])
#Youneedtoreplacetheassignmenttoretsothatthe#returnedobject:
# -isalist
# -hastherightnames(short,medium,long),and# -containsnumericandnotxtsobjects
# -andcontainsthecorrectmovingaveragevalues,whichshould# havewindowsofthecorrectsizeswhichshouldallendinthe# sameperiodwhichshouldbethelastrowofclose_prices
return(smalist)
}
getPosSignFromTMA<-function(tma_list){if(tma_list$short=1
elseif(tma_list$long>tma_list$medium&&tma_list$medium>tma_list$short)ret=-1
elseret=0
return(ret)
}
getPosSize<-function(current_closec,onstant=1000){
return(floor(constant/current_close))
}
getInSampleResult<-function(){TIme=getInSamplePeriod('x1xxx')dataList<-getData(directory="A2")
dataList<-lapply(dataList,function(x)x[TIme[1]:
TIme[2]])
lookbacks<-list(short=as.integer(5),medium=as.integer(10),long=as.integer(20))
sMult<-0.2#slippagemultiplier
newRowList=getRowList(dataList,1)numOfSeries=length(dataList)
params<-list(lookbacks=lookbacks,sdParam=1,series=1:
numOfSeries)#,posSizes=rep(1,getPosSize(newRowList[[1]]$Close)))
results<-backtest(dataList,getOrders,params,sMult)pfolioPnL<-plotResults(dataList,results)pfolioPnL$fitAgg
cat("PDratio",pfolioPnL$fitAgg)
}
getInSampleOptResult<-function(){sMult<-0.2#slippagemultiplierTIme=getInSamplePeriod('x4wl1')#####dataList<-getData(directory="A2")
dataList<-lapply(dataList,function(x)x[TIme[1]:
TIme[2]])sMult<-0.2#slippagemultiplier
numOfSeries=length(dataList)medium<-seq(from=105,to=120,by=5)short<-seq(from=100,to=110,by=5)long<-