需要你的帮助。我是新手,所以只是测试筛选策略并尝试一些代码。我有一个R数据框,价格为6个月以上的108只股票。我想只选择那些简单移动平均线大于这些股票价格均值的股票。我有以下代码来计算均值和SMA:
library(TTR)
library(quantmod)
library(FinancialInstrument)
library(PerformanceAnalytics)
library(stats)
library(tseries)
#Load Systematic investor toolbox for helpful functions
setInternet2(TRUE)
con = gzcon(url('https://github.com/systematicinvestor/SIT/raw/master/sit.gz', 'rb'))
source(con)
close(con)
tickerlist <- "funds.csv" #CSV containing tickers on rows
startDate = as.Date("2004-01-13") #Specify what date to get the prices from
maxretryattempts <- 5 #If there is an error downloading a price how many times to retry
#Load the list of ticker symbols from a csv, each row contains a ticker
stocksLst <- read.csv("funds.csv", header = F, stringsAsFactors = F)
stockData <- new.env() #Make a new environment for quantmod to store data in
nrstocks = length(stocksLst[,1]) #The number of stocks to download
#Download all the stock data
for (i in 1:nrstocks){
for(t in 1:maxretryattempts){
tryCatch(
{
if(!is.null(eval(parse(text=paste("stockData$",stocksLst[i,1],sep=""))))){
break
}
cat("(",i,"/",nrstocks,") ","Downloading ", stocksLst[i,1] , "\t\t Attempt: ", t , "/", maxretryattempts,"\n")
getSymbols(stocksLst[i,1], env = stockData, src = "yahoo", from = startDate, auto.assign=T)
}
, error = function(e) print(e))
}
}
bt.prep(stockData,align='remove.na')
price = stockData$prices
SMA_price <- apply(price[,1:108], 2, SMA, n=120)
Mean_price <- apply(price[,1:108], 2, mean)
&#39;价格&#39;是具有所有价格的数据框架。以下是它的内容预览:
head(price[,1:108])
ABA.NZ ACY.NZ AIA.NZ AIR.NZ ALF.NZ AOR.NZ ARG.NZ ATM.NZ AUG.NZ
2013-12-19 6.0 5 3.60 1.63 0.04 0.01 0.90 0.77 0.75
2013-12-20 6.3 5 3.48 1.64 0.04 0.01 0.90 0.75 0.75
2013-12-23 6.3 5 3.55 1.62 0.05 0.01 0.92 0.80 0.75
2013-12-24 6.3 5 3.57 1.62 0.05 0.01 0.92 0.80 0.75
2013-12-25 6.3 5 3.57 1.62 0.05 0.01 0.92 0.80 0.75
2013-12-26 6.3 5 3.57 1.62 0.05 0.01 0.92 0.80 0.75
知道我是如何做这项工作的吗?
感谢!!!