我需要时间序列或矩阵或矢量或数据帧吗?

时间:2018-06-13 01:37:11

标签: r

我不明白下面的代码是如何工作的。

library(quantmod)
library(PerformanceAnalytics)
library(ggplot2)
library(cowplot)
library(BatchGetSymbols)
library(tidyr)
library(quantmod)
library(xts)
library(TTR)


ticker = 'AAPL'
# Get Data
# set dates
first.date <- Sys.Date() - 360
last.date <- Sys.Date()


out <- BatchGetSymbols(ticker = ticker, 
                       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")]


##################################################################

# Eliminate Dupes
deduped_data <- unique(out[ , 1:3 ])

prices <- deduped_data$price.adjusted
prices <- as.data.frame(prices)


# Calculate Returns: Daily RoC
stock_ret <- ROC(prices, type = "discrete")


stock_ret <- as.matrix(stock_ret)
stock_ret <- ROC(stock_ret, type = "discrete")



#Output Top 10 Drawdowns By Magnitude
table.Drawdowns(stock_ret, top = 10, digits = 4)

paste("Average Drawdown",sprintf("%.2f %%", AverageDrawdown(stock_ret) * 100))
paste("Max Drawdown", sprintf("%.2f %%", maxDrawdown(stock_ret, geometric = TRUE) * 100))
paste("Drawdown Deviation",sprintf("%.2f %%", DrawdownDeviation(stock_ret) * 100))
paste("Average Length", round(AverageLength(stock_ret), 2))
paste("Average Recovery Time",round(AverageRecovery(stock_ret), 2))

当我到达下面一行时,我收到错误。

table.Drawdowns(stock_ret, top = 10, digits = 4)

Error in R[, 1, drop = FALSE] : incorrect number of dimensions

显然,变量'stock_ret'出了问题!

知道这里有什么问题吗?代码来自以下链接。

http://programmingforfinance.com/2017/11/examining-drawdowns-and-the-pain-index-with-r/

1 个答案:

答案 0 :(得分:0)

根据建议,您只需转换为xts对象即可。这似乎是最直接的方式。 xts对象需要一个日期索引。

quantmod可能已经有了这个包装器。如果有,那将更清洁。

使用默认选项,因为您显然可以处理该部分。

library(quantmod)
library(PerformanceAnalytics)
library(ggplot2)
library(cowplot)
library(BatchGetSymbols)
library(tidyr)
library(quantmod)
library(xts)
library(TTR)
ticker = 'AAPL'
# Get Data
# set dates
first.date <- Sys.Date() - 360
last.date <- Sys.Date()
out <- BatchGetSymbols(ticker = ticker, 
                       first.date = first.date,
                       last.date = last.date, 
                       cache.folder = file.path(tempdir(), 
                                                'BGS_Cache') ) 
tickers <-out$df.tickers
# Create and xts object as suggested by many of the comments
prices.xts <- xts(tickers$ret.adjusted.prices, order.by = tickers$ref.date)
str(prices.xts)
table.Drawdowns(prices.xts)