问题描述
使用quantmod或tidyquant,可以从一定范围内下载股票价格。但是,我希望将一个股票价格列添加到其中具有股票代码和日期的现有数据框中。在Google电子表格中,有一个简单的公式可以查找特定日期的股价。
=GOOGLEFINANCE("AMZN","price",date(2017,2,7))
但是,在R中,似乎没有办法。
我有一个数据框:
Date. Ticker. Revenue. Profit...
x. y z i
... ... ... ...
我需要在x上添加一个股价为y的附加列,以获取
Date. Ticker. Revenue. Profit... Price
x. y z I p (of y on x)
... ... ... ... ...
反正有这样做吗?
解决方法
您可以将tiingo与quantmod”(或tidyquant)一起使用。我希望yahoo也能正常工作,但是当使用yahoo时,如果使用1天检索(在yahoo方面比较糟糕的工作),我就会遇到错误。
import { AnalyticsService } from './providers/analytics/analytics.service';
export class AppComponent implements OnInit,OnDestroy {
constructor(
...
private analyticsService: AnalyticsService,...
) {
this.initializeApp();
}
...
initializeApp() {
this.analyticsService.startTrackerWithId('G-XXXXXXXXXX');
}
}
将所有内容组合到一个data.frame中:
library(quantmod)
my_api <- "my_api" # <- here goes your tiingo api
amzn <- getSymbols("AMZN",auto.assign = FALSE,src = "tiingo",api = my_api,from = "2017-02-07",to = "2017-02-07")
amzn
AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
2017-02-07 809.31 816.16 807.5 812.5 3466091
数据:
library(quantmod)
library(dplyr)
library(purrr)
my_api <- "my_api" # <- here goes your tiingo api
# helper function to just get the close price
get_price <- function(ticker,date) {
data <- getSymbols(ticker,from = date,to = date)
out <- as.numeric(quantmod::Cl(data))
out
}
my_data %>%
mutate(close = map2(ticker,date,get_price))
date ticker revenue profit close
1 2017-02-07 AMZN 10000 10 812.5
2 2018-03-05 MSFT 20000 20 93.64