【问题标题】:Handling xts objects that contain special characters处理包含特殊字符的 xts 对象
【发布时间】:2021-11-27 21:34:24
【问题描述】:

我想使用 tidyquant 包(或任何其他包)从 Yahoo 检索财务数据。

为了检索 Microsoft(指数:MSFT)的收盘价,以下代码可以正常工作:

#load packages
library(tidyquant)

#acquire monthly average stock prices
getSymbols("MSFT", from = "2000-08-01", to = "2021-07-31", src = 'yahoo', periodicity = 'daily')
output <- aggregate(MSFT$MSFT.Close, list(format(index(MSFT), "%Y-%m")), mean)
colnames(output) <- c('ClosingPrice')

#create time series for closing stock prices
price = ts(output$ClosingPrice, frequency=12, start=c(2000,08))
summary(price)

但是,对于检索原油价格(索引:CL=F),它不起作用,因为索引包含特殊字符。更具体地说,我在这里收到一条错误消息:

#acquire monthly average stock prices
getSymbols("CL=F", from = "2000-08-01", to = "2021-07-31", src = 'yahoo', periodicity = 'daily')
output <- aggregate(CL=F$CL=F.Close, list(format(index(MSFT), "%Y-%m")), mean)

有没有人知道如何解决这个问题?非常感谢!

【问题讨论】:

    标签: r yahoo-finance yahoo-api tidyquant


    【解决方案1】:

    带有特殊字符的对象名称可以反引号。此外,如果有 NA 值,请指定 na.rm = TRUEna.action = NULLaggregate 可以删除整行,如果有 NA 在任何列中

    out <- aggregate(`CL=F`$`CL=F.Close`, list(format(index(`CL=F`), "%Y-%m")), 
           mean, na.rm = TRUE, na.action = NULL)
    

    -输出

    > head(out)
                    
    2000-08 32.54571
    2000-09 33.87100
    2000-10 32.97318
    2000-11 34.26450
    2000-12 28.35500
    2001-01 29.26667
    > tail(out)
                    
    2021-02 59.06105
    2021-03 62.35739
    2021-04 61.70381
    2021-05 65.15700
    2021-06 71.35273
    2021-07 72.43048
    

    【讨论】:

    • 非常感谢!能简单解释一下普通引号和反引号的区别吗?
    • @natalieee 如果您检查?Quotes Backticks are used for non-standard variable names.。允许的名称带有下划线和字母数字字符。以数字开头的对象也是非标准的
    • 好吧,干杯.. 学到了新东西!
    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    相关资源
    最近更新 更多