首页 > 解决方案 > 如何使用 `tempdisagg` 包中的 `td` 命令将每月数据分解为每日数据频率?

问题描述

我有一个每月频率数据,我试图将其分解为每日频率数据。因此,我使用以下代码在 R 中使用包中的td命令:tempdisagg

 dat=ts(data[,2])
 result=td(dat~1, conversion = "average", to = "day", method = "chow-lin-maxlog")

然后我收到以下错误消息:

 Error in td(dat ~ 1, conversion = "average", to = "day", method = "chow-lin-maxlog") : 'to' argument: unknown character string

我使用的数据dat如下:

在此处输入图像描述

 > dput(head(dat))
 c(82.47703009, 84.63094431, 70.00659987, 78.81135651, 74.749746,82.95638213)

所以虽然这个数据dat是按月计算的,但开始和结束还没有反映这一点。实际上,开始日期是 1/1997,结束日期是 9/2019。

请问我可以帮助我将这个月度数据dat分解为每日频率数据吗?

标签: rstatisticstime-seriessyntax-errorfrequency

解决方案


看起来 tempdisagg 包不允许每月到每天的分解。从td()帮助文件“到”参数:

高频目标频率作为字符串(“季度”或“月度”)或标量(例如 2、4、7、12)。如果输入序列是 ts 对象,则如果没有给出指示符,则该参数是必需的。如果输入序列是向量,则 to 必须是指示频率比的标量。

您的错误消息“'to' argument: unknown character string”是因为该to =参数仅接受 ' Quarterly' 或 'monthly' 作为字符串。

这里有一些关于将每月数据分解为每日统计数据堆栈交换的讨论: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))

以下是三个图表,显示 1. 仅每月回报,2. 每月回报的日平均值,3. 两者一起。由于它们是相同的,因此第三张图像中的过度绘图仅显示了一个。

每月回报

每月回报的每日平均回报

每月和每日平均一起绘制


推荐阅读