代码之家  ›  专栏  ›  技术社区  ›  ASH

试图将股票行情与调整后的指数相匹配。价格

r
  •  0
  • ASH  · 技术社区  · 6 年前

    我无法在下面的股票价格列表中找到一个合适的日期。我得到了25支股票,标题如下:$df。股票行情,价格。开门,普莱斯。价格很高。价格低。成交,成交价。调整

    有一件事我搞不清楚,当我输入'out'时,我得到的是数据集,但当我输入dim(out)时,我得到的是空值。这毫无意义。无论如何,我正在尝试从下面的链接运行代码。

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

    我相信谷歌API去年被关闭了,因此,你不能再从谷歌那里获得历史股价。你有没有想过该怎么做?谢谢

    1 回复  |  直到 6 年前
        1
  •  1
  •   Esther    6 年前

    本教程使用的是“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])