我正在更新一些遗留代码,这些代码正在提取价格数据并使用
quantmod
包来计算每日回报、标准差、双周回报(10 天)和双周标准差。与旧方法相比,新的 API 调用正确地为我正在查看的 ID 提取了相同的值。但是,当我复制相同的 Delt()
和 sd
函数时,结果不同,我不明白为什么。这是我正在运行的代码:
#### Legacy code ####
AllPrices <- F.ExtractFormulaHistory(master, StringA, StringB);
for(i in 1:length(master)){
Prices <- AllPrices[AllPrices$Id == master[i],];
Prices <- Prices[is.na(Prices$fg.price) == FALSE,];
if (length(Prices$fg.price) > 252) {
## print(i);
Prices$DailyRet <- Delt(Prices$fg.price);
Prices$DailySD <- rollapply(Prices$DailyRet, width = 252, FUN = sd, fill = NA, align = "right") * sqrt(252);
Prices$BiWeeklyRet <- Delt(Prices$fg.price, k = 10);
Prices$BiWeeklySD <- rollapply(Prices$BiWeeklyRet, width = 252, FUN = sd, fill = NA, align = "right") * sqrt(25.2);
write.table(Prices, file = MPTempFN, append = TRUE, sep = ",", col.names = FALSE, row.names = TRUE, qmethod = "double");
}
}
### My code, note i needed to invert the price of DailyRet as it was giving me the opposite of what
### I was looking for.
## Extract Price, ID, and Date columns
ID <- AllPrices$requestId
Price <- AllPrices$P_PRICE.0..400.D.
Date <- as.Date(AllPrices$date)
## Calculate daily returns
DailyRet <- (Delt(Price, k = 1)) * -1
## Calculate rolling 252-day standard deviation of daily returns
DailySD <- rollapply(DailyRet, width = 252, FUN = sd, fill = NA, align = "right") * sqrt(252)
## Calculate bi-weekly returns
BiWeeklyRet <- Delt(Price, k = 10)
## Calculate rolling 252-day standard deviation of bi-weekly returns
BiWeeklySD <- rollapply(BiWeeklyRet, width = 252, FUN = sd, fill = NA, align = "right") * sqrt(25.2)
## Combine results into a data frame
Prices <- data.frame(ID, Date, Price, DailyRet, DailySD, BiWeeklyRet, BiWeeklySD)
colnames(Prices) <- c("ID", "Date","Price", "DailyRet", "DailySD", "BiWeeklyRet", "BiWeeklySD")
Prices$Date <- Date
## Save results to a CSV file
write.csv(Prices, file = "Prices.csv", row.names = FALSE)
我已经包含了我正在写入 csv 的结果,并手动检查我的新代码是否正常工作。
,每天的 ret 计算正确,但是这些值被我需要修复的一行抵消了。
我试图尽可能地复制代码的旧格式。确保首先,我的价格值是正确的,其次,那里没有问题。我能够重现每日回报函数,但我的双周和标准偏差继续关闭。