Eri*_*ric 9 statistics r time-series frequency syntax-error
我有一个每月频率数据,我试图将其分解为每日频率数据。因此,我使用R 中td的tempdisagg包中的命令使用以下代码:
dat=ts(data[,2])
result=td(dat~1, conversion = "average", to = "day", method = "chow-lin-maxlog")
Run Code Online (Sandbox Code Playgroud)
然后我收到以下错误消息:
Error in td(dat ~ 1, conversion = "average", to = "day", method = "chow-lin-maxlog") : 'to' argument: unknown character string
Run Code Online (Sandbox Code Playgroud)
我使用的数据dat如下:
> dput(head(dat))
c(82.47703009, 84.63094431, 70.00659987, 78.81135651, 74.749746,82.95638213)
Run Code Online (Sandbox Code Playgroud)
所以虽然这个数据dat是月频,但是开始和结束还没有反映这个。实际上,开始日期是 1/1997,结束日期是 9/2019。
请问我可以帮忙把这个月度数据dat分解成每日频率数据吗?
看起来 tempdisagg 包不允许按月到每日进行分类。从td()帮助文件“to”参数:
高频目标频率为字符串(“季度”或“每月”)或标量(例如 2、4、7、12)。如果输入系列是 ts 对象,如果没有给出指示符,则该参数是必需的。如果输入序列是向量,则 to 必须是表示频率比的标量。
您的错误消息“'to'参数:未知字符串”是因为该to =参数仅接受“季度”或“每月”作为字符串。
这里有一些关于统计 stackexchage 上将每月数据分解为每日数据的讨论:https ://stats.stackexchange.com/questions/258810/disaggregate-monthly-forecasts-into-daily-data
经过一番搜索后,似乎没有人持续使用每月到每日的分类数据。该tempdisagg软件包似乎能够实现大多数其他人认为可行的功能——每年到季度或每月,并且时间段一致甚至是倍数。
埃里克,我在下面添加了一个脚本,据我所知,它应该说明您想要做什么。
在这里,我们使用真实的定价数据,从每日价格 -> 每月价格 -> 每月回报 -> 平均每日回报。
library(quantmod)
library(xts)
library(zoo)
library(tidyverse)
library(lubridate)
# Get price data to use as an example
getSymbols('MSFT')
#This data has more information than we want, remove unwanted columns:
msft <- Ad(MSFT)
#Add new column that acts as an 'indexed price' rather than
# actual price data. This is to show that calculated returns
# don't depend on real prices, data indexed to a value is fine.
msft$indexed <- scale(msft$MSFT.Adjusted, center = FALSE)
#split into two datasets
msft2 <- msft$indexed
msft$indexed <- NULL
#msft contains only closing data, msft2 only contains scaled data (not actual prices)
# move from daily data to monthly, to replicate the question's situation.
a <- monthlyReturn(msft)
b <- monthlyReturn(msft2)
#prove returns based on rescaled(indexed) data and price data is the same:
all.equal(a,b)
# subset to a single year
a <- a['2019']
b <- b['2019']
#add column with days in each month
a$dim <- days_in_month(a)
a$day_avg <- a$monthly.returns / a$dim ## <- This must've been left out
day_avgs <- data.frame(day_avg = rep(a$day_avg, a$dim))
# daily averages timesereis from monthly returns.
z <- zoo(day_avgs$day_avg,
seq(from = as.Date("2019-01-01"),
to = as.Date("2019-12-31"),
by = 1)) %>%
as.xts()
#chart showing they are the same:
PerformanceAnalytics::charts.PerformanceSummary(cbind(a$monthly.returns, z))
Run Code Online (Sandbox Code Playgroud)
以下三张图表显示 1. 仅每月回报,2. 每月回报的每日平均回报,3. 两者一起。由于它们是相同的,因此第三张图像中的过度绘制仅显示了一个。