R getSymbols下载多个符号的数据并计算返回值

R getSymbols下载多个符号的数据并计算返回值,r,loops,quantmod,stocks,R,Loops,Quantmod,Stocks,我目前正在使用Quantmod包中的GetSymbols下载股票数据,并计算每日股票收益率,然后将数据合并到数据框中。我想这样做的一个非常大的股票符号集。见下面的例子。如果可能的话,我想使用For循环,或者使用apply函数,但是我找不到解决方案 这就是我目前所做的: Symbols<-c ("XOM","MSFT","JNJ","GE","CVX","WFC","PG","JPM","VZ","PFE","T","IBM","MRK","BAC","DIS","ORCL","PM","

我目前正在使用Quantmod包中的GetSymbols下载股票数据,并计算每日股票收益率,然后将数据合并到数据框中。我想这样做的一个非常大的股票符号集。见下面的例子。如果可能的话,我想使用For循环,或者使用apply函数,但是我找不到解决方案

这就是我目前所做的:

Symbols<-c  ("XOM","MSFT","JNJ","GE","CVX","WFC","PG","JPM","VZ","PFE","T","IBM","MRK","BAC","DIS","ORCL","PM","INTC","SLB")
length(Symbols)

#daily returns for selected stocks & SP500 Index
SP500<-as.xts(dailyReturn(na.omit(getSymbols("^GSPC",from=StartDate,auto.assign=FALSE))))
S1<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[1],from=StartDate,auto.assign=FALSE))))
S2<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[2],from=StartDate,auto.assign=FALSE))))
S3<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[3],from=StartDate,auto.assign=FALSE))))
S4<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[4],from=StartDate,auto.assign=FALSE))))
S5<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[5],from=StartDate,auto.assign=FALSE))))
S6<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[6],from=StartDate,auto.assign=FALSE))))
S7<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[7],from=StartDate,auto.assign=FALSE))))
S8<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[8],from=StartDate,auto.assign=FALSE))))
S9<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[9],from=StartDate,auto.assign=FALSE))))
S10<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[10],from=StartDate,auto.assign=FALSE)))) 
....
S20<-as.xts(dailyReturn(na.omit(getSymbols(Symbols[20],from=StartDate,auto.assign=FALSE)))) 

SPportD<-cbind(SP500,S1,S2,S3,S4,S5,S6,S7,S8,S9,S10,S11,S12,S13,S14,S15,S16,S17,S18,S19,S20)
names(SPportD)[1:(length(Symbols)+1)]<-c("SP500",Symbols)

SPportD.df<-data.frame(index(SPportD),coredata(SPportD),stringsAsFactors=FALSE)
names(SPportD.df)[1:(length(Symbols)+2)]<-c(class(StartDate),"SP500",Symbols)

Symbols
lappy
是你的朋友:

Stocks = lapply(Symbols, function(sym) {
  dailyReturn(na.omit(getSymbols(sym, from=StartDate, auto.assign=FALSE)))
})
然后要合并:

do.call(merge, Stocks)

其他作业的类似应用程序是您的朋友:

Stocks = lapply(Symbols, function(sym) {
  dailyReturn(na.omit(getSymbols(sym, from=StartDate, auto.assign=FALSE)))
})
然后要合并:

do.call(merge, Stocks)

其他作业

软件包的类似应用程序包括用于数据下载的
quantmod
,以及用于分析/绘图的
PerformanceAnalytics

必须注意时间序列日期对齐

代码

require(quantmod)
require(PerformanceAnalytics)


Symbols<-c  ("XOM","MSFT","JNJ","GE","CVX","WFC","PG","JPM","VZ","PFE","T","IBM","MRK","BAC","DIS","ORCL","PM","INTC","SLB")
length(Symbols)

#Set start date
start_date=as.Date("2014-01-01")

#Create New environment to contain stock price data
dataEnv<-new.env()

#download data          
getSymbols(Symbols,env=dataEnv,from=start_date)


#You have 19 symbols, the time series data for all the symbols might not be aligned 


#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)

#helper function for extracting Closing price of getsymbols output and for date alignment 

bt.prep(dataEnv,align='remove.na')

#Now all your time series are correctly aligned

#prices data

stock_prices = dataEnv$prices
head(stock_prices[,1:3])
# head(stock_prices[,1:3])
#             BAC    CVX   DIS
#2014-01-02 16.10 124.14 76.27
#2014-01-03 16.41 124.35 76.11
#2014-01-06 16.66 124.02 75.82
#2014-01-07 16.50 125.07 76.34
#2014-01-08 16.58 123.29 75.22
#2014-01-09 16.83 123.29 74.90

 #calculate returns
 stock_returns = Return.calculate(stock_prices, method = c("discrete"))
 head(stock_returns[,1:3])
# head(stock_returns[,1:3])
#                    BAC          CVX          DIS
#2014-01-02           NA           NA           NA
#2014-01-03  0.019254658  0.001691638 -0.002097810
#2014-01-06  0.015234613 -0.002653800 -0.003810275
#2014-01-07 -0.009603842  0.008466376  0.006858349
#2014-01-08  0.004848485 -0.014232030 -0.014671208
#2014-01-09  0.015078408  0.000000000 -0.004254188

#Plot Performance for first three stocks
charts.PerformanceSummary(stock_returns[,1:3],main='Stock Absolute Performance',legend.loc="bottomright")
require(quantmod)
要求(性能分析)

符号包是用于数据下载的
quantmod
,用于分析/绘图的
PerformanceAnalytics

必须注意时间序列日期对齐

代码

require(quantmod)
require(PerformanceAnalytics)


Symbols<-c  ("XOM","MSFT","JNJ","GE","CVX","WFC","PG","JPM","VZ","PFE","T","IBM","MRK","BAC","DIS","ORCL","PM","INTC","SLB")
length(Symbols)

#Set start date
start_date=as.Date("2014-01-01")

#Create New environment to contain stock price data
dataEnv<-new.env()

#download data          
getSymbols(Symbols,env=dataEnv,from=start_date)


#You have 19 symbols, the time series data for all the symbols might not be aligned 


#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)

#helper function for extracting Closing price of getsymbols output and for date alignment 

bt.prep(dataEnv,align='remove.na')

#Now all your time series are correctly aligned

#prices data

stock_prices = dataEnv$prices
head(stock_prices[,1:3])
# head(stock_prices[,1:3])
#             BAC    CVX   DIS
#2014-01-02 16.10 124.14 76.27
#2014-01-03 16.41 124.35 76.11
#2014-01-06 16.66 124.02 75.82
#2014-01-07 16.50 125.07 76.34
#2014-01-08 16.58 123.29 75.22
#2014-01-09 16.83 123.29 74.90

 #calculate returns
 stock_returns = Return.calculate(stock_prices, method = c("discrete"))
 head(stock_returns[,1:3])
# head(stock_returns[,1:3])
#                    BAC          CVX          DIS
#2014-01-02           NA           NA           NA
#2014-01-03  0.019254658  0.001691638 -0.002097810
#2014-01-06  0.015234613 -0.002653800 -0.003810275
#2014-01-07 -0.009603842  0.008466376  0.006858349
#2014-01-08  0.004848485 -0.014232030 -0.014671208
#2014-01-09  0.015078408  0.000000000 -0.004254188

#Plot Performance for first three stocks
charts.PerformanceSummary(stock_returns[,1:3],main='Stock Absolute Performance',legend.loc="bottomright")
require(quantmod)
要求(性能分析)

符号
dailyReturn
使用收盘价,因此我建议您在调用
dailyReturn
之前,使用不同的函数(例如调整列上的
TTR::ROC
),或者调整股息/分割的收盘价(使用
adjustOHLC

library(quantmod)
Symbols <- c("XOM","MSFT","JNJ","GE","CVX","WFC","PG","JPM","VZ","PFE",
             "T","IBM","MRK","BAC","DIS","ORCL","PM","INTC","SLB")
# create environment to load data into
Data <- new.env()
getSymbols(c("^GSPC",Symbols), from="2007-01-01", env=Data)    
# calculate returns, merge, and create data.frame (eapply loops over all
# objects in an environment, applies a function, and returns a list)
Returns <- eapply(Data, function(s) ROC(Ad(s), type="discrete"))
ReturnsDF <- as.data.frame(do.call(merge, Returns))
# adjust column names are re-order columns
colnames(ReturnsDF) <- gsub(".Adjusted","",colnames(ReturnsDF))
ReturnsDF <- ReturnsDF[,c("GSPC",Symbols)]
库(quantmod)

符号
dailyReturn
使用收盘价,因此我建议您在调用
dailyReturn
之前,使用不同的函数(例如调整列上的
TTR::ROC
),或者调整股息/分割的收盘价(使用
adjustOHLC

library(quantmod)
Symbols <- c("XOM","MSFT","JNJ","GE","CVX","WFC","PG","JPM","VZ","PFE",
             "T","IBM","MRK","BAC","DIS","ORCL","PM","INTC","SLB")
# create environment to load data into
Data <- new.env()
getSymbols(c("^GSPC",Symbols), from="2007-01-01", env=Data)    
# calculate returns, merge, and create data.frame (eapply loops over all
# objects in an environment, applies a function, and returns a list)
Returns <- eapply(Data, function(s) ROC(Ad(s), type="discrete"))
ReturnsDF <- as.data.frame(do.call(merge, Returns))
# adjust column names are re-order columns
colnames(ReturnsDF) <- gsub(".Adjusted","",colnames(ReturnsDF))
ReturnsDF <- ReturnsDF[,c("GSPC",Symbols)]
库(quantmod)

符号而不是一次传递一个符号使用
getSymbols(Symbols,…)
查看此链接()获取更多点而不是一次传递一个符号使用
getSymbols(Symbols,…)
查看此链接()获取更多点谢谢Hugh,一个问题,如何将列表转换为数据帧?由于列表中有20个xts对象。嗨,休,已经得到了答案:Stocks1使用
do.call(merge.xts,Stocks)
将xts数据与时间索引合并,而不是
cbind
,后者只会堆叠列Osssan的注释是否完成此答案,New_code?
lappy(符号,函数(sym)dailyReturn(na.omit)(getSymbols(sym,from=StartDate,auto.assign=FALSE))
将更干净,并且不容易输入错误的整数序列进行循环。谢谢Hugh,我有一个问题,如何将列表转换为数据帧?因为列表有20个xts对象。Hi Hugh,已经得到了答案:Stocks1use
do.call(merge.xts,Stocks)
将xts数据与时间索引合并,而不是将列堆叠起来的
cbind
奥桑的评论是否完成此回答,新代码?
lapply(符号,函数(sym)dailReturn(na.omit(getSymbols(sym,from=StartDate,auto.assign=FALSE)))
将更干净,更不容易错误地输入错误的整数序列进行循环。嗨,Joshua,谢谢你的代码。很有趣。你知道为什么在eapply下,顺序会发生变化吗?@New\u code:因为你无法定义环境中对象的顺序。它不是字母顺序,也不是ob的顺序对象被创建。嗨,Joshua,谢谢你的代码。很有趣。你知道为什么在eapply下,顺序会改变吗?@New\u code:因为你不能定义环境中对象的顺序。它不是字母顺序,也不是对象创建的顺序。