您好,欢迎访问三七文档
当前位置:首页 > 金融/证券 > 股票报告 > R语言预测股票市场收益
预测股票市场收益1.读取数据:install.packages(zoo)install.packages(xts)install.packages(tseries)library(xts)library(tseries)GSPC-as.xts(get.hist.quote(^GSPC,start=1970-01-02,end='2009-09-15',quote=c(Open,High,Low,Close,Volume,AdjClose)))head(GSPC)2.绘制股票曲线p-apply(GSPC[,2:4],1,mean)t-function(p,close,tgt=0.025,m=10){n-length(p)v-numeric(length=n-m)for(iin1:(n-m)){v[i]-(p[i+m]-close[i])/close[i]}num-length(v)-mt-numeric(length=num)for(iin1:num){t[i]-sum(v[i:(i+m-1)])}plot(t,type=h,lwd=0.1)}t(p,GSPC$Close)3.K线图T.ind-function(quotes,tgt.margin=0.025,n.days=10){v-apply(HLC(quotes),1,mean)r-matrix(NA,ncol=n.days,nrow=NROW(quotes))for(xin1:n.days)r[,x]-Next(Delt(v,k=x),x)x-apply(r,1,function(x)sum(x[xtgt.margin|x-tgt.margin]))if(is.xts(quotes))xts(x,time(quotes))elsex}candleChart(last(GSPC,'3months'),theme='white',TA=NULL)avgPrice-function(p)apply(HLC(p),1,mean)addAvgPrice-newTA(FUN=avgPrice,col=1,legend='AvgPrice')addT.ind-newTA(FUN=T.ind,col='red',legend='tgtRet')addAvgPrice(on=1)addT.ind()4.用随机森林选择变量myATR-function(x)ATR(HLC(x))[,'atr']mySMI-function(x)SMI(HLC(x))[,'SMI']myADX-function(x)ADX(HLC(x))[,'ADX']myAroon-function(x)aroon(x[,c('High','Low')])$oscillatormyBB-function(x)BBands(HLC(x))[,'pctB']myChaikinVol-function(x)Delt(chaikinVolatility(x[,c(High,Low)]))[,1]myCLV-function(x)EMA(CLV(HLC(x)))[,1]myEMV-function(x)EMV(x[,c('High','Low')],x[,'Volume'])[,2]myMACD-function(x)MACD(Cl(x))[,2]myMFI-function(x)MFI(x[,c(High,Low,Close)],x[,Volume])mySAR-function(x)SAR(x[,c('High','Close')])[,1]myVolat-function(x)volatility(OHLC(x),calc=garman)[,1]data(GSPC)install.packages(quantmod)library(TTR)library(Defaults)library(quantmod)library(randomForest)data.model-specifyModel(T.ind(GSPC)~Delt(Cl(GSPC),k=1:10)+myATR(GSPC)+mySMI(GSPC)+myADX(GSPC)+myAroon(GSPC)+myBB(GSPC)+myChaikinVol(GSPC)+myCLV(GSPC)+CMO(Cl(GSPC))+EMA(Delt(Cl(GSPC)))+myEMV(GSPC)+myVolat(GSPC)+myMACD+myMFI(GSPC)+RSI(Cl(GSPC))+mySAR(GSPC)+runMean(Cl(GSPC))+runSD(Cl(GSPC)))set.seed(1234)rf-buildModel(data.model,method='randomForest',training.per=c(start(GSPC),index(GSPC[1999-12-31])),ntree=50,importance=T)varImpPlot(rf@fitted.model,type=1)5.变量选择imp-importance(af@fitted.model,type=1)rownames(imp)[which(imp10)][1]Delt.Cl.GSPC.k.1.10.Delt.1.arithmetic[2]myATR.GSPC[3]myADX.GSPC[4]myEMV.GSPC[5]myVolat.GSPC[6]myMACD.GSPC[7]mySAR.GSPC[8]runMean.Cl.GSPC6.建立模型数据集data.model-specifyModel(T.ind(GSPC)~Delt(Cl(GSPC),k=1)myATR(GSPC)+myADX(GSPC)+myEMV(GSPC)+myVolat(GSPC)+myMACD(GSPC)+mySAR(GSPC)+runMean(Cl(GSPC)))
本文标题:R语言预测股票市场收益
链接地址:https://www.777doc.com/doc-5571172 .html