我有下面的脚本可以很好地提取历史股票价格,但我似乎无法按照调整后的价格获得一份代码清单。我有25个股票,标题看起来像这样:$ df.tickers,price.open,price.high,price.low,price.close,volume price.adjusted
我无法弄清楚的一点是,当我输入' out'我得到了数据集,但是当我输入dim(out)时,我得到一个null。这没有任何意义。无论如何,我试图从下面的链接运行代码。
http://programmingforfinance.com/2017/10/portfolio-optimization-with-r/
以下是我正在使用的代码。
library(BatchGetSymbols)
library(sqldf)
library(dplyr)
# set dates
first.date <- Sys.Date() - 360
last.date <- Sys.Date()
# set tickers
tickers <- c('MMM','ABT','ABBV','ABMD',
'ACN','ATVI','AYI','ADBE','AMD','AAP',
'AES','AET','AMG','AFL','A','APD','AKAM',
'ALK','ALB','ARE','ALXN','ALGN','ALLE','AGN','ADS')
out <- BatchGetSymbols(tickers = tickers,
first.date = first.date,
last.date = last.date,
cache.folder = file.path(tempdir(),
'BGS_Cache') ) # cache in tempdir()
# dim(out$df.tickers)
# 6175 10
# After downloading the data, we can check the success of the process for each ticker.
# Notice that the last ticker does not exist in yahoo finance or google and therefore
# results in an error. All information regarding the download process is provided in the dataframe df.control:
# print(out$df.control)
price_adjusted <- as.data.frame(out)
price_final <- subset(price_adjusted, select = c(df.control.ticker, df.tickers.price.adjusted, df.tickers.ref.date))
# df_final <- subset(price_final, df.control.ticker == 'MMM', select = c("df.control.ticker","df.tickers.price.adjusted","df.tickers.ref.date"))
我认为Google API在去年被关闭了,因此,您无法再获得Google的历史股票价格。有关如何使这项工作的任何想法?谢谢!
答案 0 :(得分:1)
本教程使用'xts'时间序列格式的数据。要转换您的数据,
library(BatchGetSymbols)
library(tidyr)
library(quantmod)
# set dates
first.date <- Sys.Date() - 360
last.date <- Sys.Date()
# set tickers
tickers <- c('MMM','ABT','ABBV','ABMD',
'ACN','ATVI','AYI','ADBE','AMD','AAP',
'AES','AET','AMG','AFL','A','APD','AKAM',
'ALK','ALB','ARE','ALXN','ALGN','ALLE','AGN','ADS')
out <- BatchGetSymbols(tickers = tickers,
first.date = first.date,
last.date = last.date,
cache.folder = file.path(tempdir(),
'BGS_Cache') )
out<-out$df.tickers
out<-out[,c("ref.date","ticker", "price.adjusted")]
q <- spread(out, ticker, price.adjusted)
portfolioPrices <- xts(q[,-1], order.by=q[,1])