用R回溯股市

问题描述 投票:0回答:1

我是R的新用户,并希望使用R来回测我的策略。我尝试结合在web中找到的一些脚本。但是,它根据我的想法不起作用。我的问题是根据我的策略设计日期无法生成交易日期。

library(quantmod)
library(lubridate)
stock1<-getSymbols("AAPL",src="yahoo",from="2016-01-01",auto.assign=F)

stock1<-na.locf(stock1)
stock1$EMA9<-EMA(Cl(stock1),n=9)
stock1$EMA19<-EMA(Cl(stock1),n=19)
stock1$EMACheck<-ifelse(stock1$EMA9>stock1$EMA19,1,0)
stock1$EMA_CrossOverUp<-ifelse(diff(stock1$EMACheck)==1,1,0)
stock1$EMA_CrossOverDown<-ifelse(diff(stock1$EMACheck)==-1,-1,0)

stock1<-stock1[index(stock1)>="2016-01-01",]

stock1_df<-data.frame(index(stock1),coredata(stock1))

colnames(stock1_df)<-c("Date","Open","High","Low","Close","Volume","Adj","EMA9","EMA19","EMACheck","EMACheck_up","EMACheck_down")

#To calculate the number of crossoverup transactions during the duration from 2016-01-01

sum(stock1_df$EMACheck_up==1 & index(stock1)>="2016-01-01",na.rm=T)

stock1_df$Date[stock1_df$EMACheck_up==1 & index(stock1)>="2016-01-01"]

sum(stock1_df$EMACheck_down==-1 & index(stock1)>="2016-01-01",na.rm=T)

stock1_df$Date[stock1_df$EMACheck_down==-1 & index(stock1)>="2016-01-01"]

#To generate the transcation according to the strategy

transaction_dates<-function(stock2,Buy,Sell)
{
Date_buy<-c()
Date_sell<-c()
hold<-F
stock2[["Hold"]]<-hold
for(i in 1:nrow(stock2)) {
  if(hold == T) {
    stock2[["Hold"]][i]<-T
    if(stock2[[Sell]][i] == -1) {
      #stock2[["Hold"]][i]<-T
      hold<-F
    }
  } else {
    if(stock2[[Buy]][i] == 1) {
      hold<-T
      stock2[["Hold"]][i]<-T
    }
  }
}


stock2[["Enter"]]<-c(0,ifelse(diff(stock2[["Hold"]])==1,1,0))
stock2[["Exit"]]<-c(ifelse(diff(stock2[["Hold"]])==-1,-1,0),0)

Buy_date <- stock2[["Date"]][stock2[["Enter"]] == 1]
Sell_date <- stock2[["Date"]][stock2[["Exit"]] == -1]

if (length(Sell_date)<length(Buy_date)){
  #Sell_date[length(Sell_date)+1]<-tail(stock2[["Date"]],n=2)[1]
  Buy_date<-Buy_date[1:length(Buy_date)-1]

}

return(list(DatesBuy=Buy_date,DatesSell=Sell_date))
}

#transaction dates generate:
stock1_df <- na.locf(stock1_df)

transactionDates<-transaction_dates(stock1_df,"EMACheck_up","EMACheck_down")

transactionDates

num_transaction1<-length(transactionDates[[1]])

Open_price<-function(df,x) {df[as.integer(rownames(df[df[["Date"]]==x,]))+1,][["Open"]]}
transactions_date<-function(df,x) {df[as.integer(rownames(df[df[["Date"]]==x,]))+1,][["Date"]]}

transactions_generate<-function(df,num_transaction)
{
price_buy<-sapply(1:num_transaction,function(x) {Open_price(df,transactionDates[[1]][x])})
price_sell<-sapply(1:num_transaction,function(x) {Open_price(df,transactionDates[[2]][x])})
Dates_buy<-as.Date(sapply(1:num_transaction,function(x) {transactions_date(df,transactionDates[[1]][x])}))
Dates_sell<-as.Date(sapply(1:num_transaction,function(x) {transactions_date(df,transactionDates[[2]][x])}))


transactions_df<-data.frame(DatesBuy=Dates_buy,DatesSell=Dates_sell,pricesBuy=price_buy,pricesSell=price_sell)
#transactions_df$return<-100*(transactions_df$pricesSell-transactions_df$pricesBuy)/transactions_df$pricesBuy
transactions_df$Stop_loss<-NA
return(transactions_df)
}

transaction_summary<-transactions_generate(stock1_df,num_transaction1)
transaction_summary$Return<-100*(transaction_summary$pricesSell-transaction_summary$pricesBuy)/transaction_summary$pricesBuy
transaction_summary

sum(transaction_summary$Return,na.rm=T)

嗨,我是R的新用户,并希望使用R来回测我的策略。我尝试结合在web中找到的一些脚本。但是,它根据我的想法不起作用。我的问题是根据我的策略设计日期无法生成交易日期。

problem as this image

r back
1个回答
0
投票

你拥有的代码就是为了自己的利益而复杂化。

问题在于Open_price和transactions_date函数寻找使用rownames来查找记录号然后接下来的记录号。但是,它不是再次寻找rownames,而是用作索引。那里出错了。

如果您查看第一个日期的以下结果,则返回40。

as.integer(rownames(stock1_df[stock1_df[["Date"]] == "2016-03-01", ]))
[1] 40

因此,它所寻找的下一条记录将是41.但是stock_df [41,]与rowname 41不同.rownames的一个问题是,如果你从data.frame过滤/删除记录,则rownames不会改变。要获得正确的索引号,您应该使用which。如果你看一下stock1_df,你可以看到它返回21,我们需要记录22

which(stock1_df[["Date"]] == "2016-03-01")
[1] 21

我更改了Open_price和transactions_date函数以使用which函数。现在,这将返回正确的结果。

Open_price <- function(df, x) {
  df[which(df[["Date"]] == x) + 1, ][["Open"]]
}

transactions_date <- function(df, x) {
  df[which(df[["Date"]] == x) + 1, ][["Date"]]
}


head(transaction_summary)
     DatesBuy  DatesSell pricesBuy pricesSell Stop_loss    Return
1  2016-03-02 2016-04-25    100.51     105.00        NA  4.467215
2  2016-05-27 2016-06-20     99.44      96.00        NA -3.459374
3  2016-07-13 2016-09-12     97.41     102.65        NA  5.379322
4  2016-09-15 2016-11-02    113.86     111.40        NA -2.160547
5  2016-12-12 2017-06-13    113.29     147.16        NA 29.896728
6  2017-07-17 2017-09-19    148.82     159.51        NA  7.183166

一些建议,尝试在代码中使用空格。这使它更具可读性。以这个style guide为例。您的整个代码将被重写为仅使用stock1,而无需将代码转换为data.frame。但是现在代码完成了它需要做的事情。

© www.soinside.com 2019 - 2024. All rights reserved.