2015-12-10 33 views
0

我收到來自投資組合分析包的以下錯誤。PortfolioAnalytics錯誤行名稱不是日期

Error in checkData(R) : 
    The data cannot be converted into a time series. If you are trying to pass in names from a data object with one column, you should use the form 'data[rows, columns, drop = FALSE]'. Rownames should have standard date formats, such as '1985-03-15'. 

我使用的數據集是模擬數據

> df 
     X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 
[1,] 0 1 0 1 0 0 0 1 1 0 
[2,] 0 1 0 0 1 1 1 1 1 1 
[3,] 1 0 0 0 0 0 0 1 1 0 
[4,] 1 0 1 1 1 0 0 1 0 1 
[5,] 0 0 1 0 1 0 1 1 1 0 
[6,] 0 1 0 1 0 1 1 0 1 1 
[7,] 1 0 0 0 0 1 1 1 1 0 
[8,] 0 0 1 1 0 0 1 1 0 1 
[9,] 1 0 0 0 0 1 1 1 1 0 
[10,] 0 1 1 0 0 1 0 1 0 0 

我設置了投資組合的限制是

returns = as.matrix(df) 
> funds = colnames(df) 
> init.portfolio <- portfolio.spec(assets = funds) 
> init.portfolio <- add.constraint(portfolio = init.portfolio, type = "full_investment") 
> init.portfolio <- add.constraint(portfolio = init.portfolio, type = "long_only") 
> minSD.portfolio <- add.objective(portfolio=init.portfolio, 
+         type="risk", 
+         name="StdDev") 
> minSD.opt <- optimize.portfolio(R = df, portfolio = minSD.portfolio, 
+  optimize_method = "ROI", trace = TRUE) 
Error in checkData(R) : 
    The data cannot be converted into a time series. If you are trying to pass in names from a data object with one column, you should use the form 'data[rows, columns, drop = FALSE]'. Rownames should have standard date formats, such as '1985-03-15'. 

我怎樣才能解決這個錯誤。 DF是單週期收益的模擬。所以他們都是100%或0%,並在同一時期。如果我需要作爲行名稱,我可以添加一個日期變量,但我不知道如何。我試過

> rownames(df) = as.Date(c("Jan", rep(nrow(df)))) 
Error in charToDate(x) : 
    character string is not in a standard unambiguous format 

有人可以幫我解決這個錯誤嗎?謝謝

回答

2

您需要將日期數據添加到df。假設數據是在今年內的開頭開始的月度回報率,您可以使用

rownames(df) <- as.character(seq(as.Date("2015-01-01"), length.out=nrow(df), by = "month")) 

要麼添加rownames或轉換DF到XTS通過

library(xts) 
df <- xts(df, order.by = seq(as.Date("2015-01-01"), 
            length.out=nrow(df), by = "month"), df) 

xts時間序列是一種常用的格式對於財務時間序列並且適用於PortfolioAnalytics,因此您可能會考慮這一點。

一旦你完成了並運行optimize.portfolio,你將不會得到解決方案。看起來df不是肯定的,所以你必須調整df中的值。

此外,我不太理解你的評論,單一期間的回報要求返回值爲0或1.這通常是不正確的。

+0

這些是模擬的投注結果,勝利有相關性。我正在嘗試獲得投注的最大夏普比率(回報/標準差)。正在努力與優化。 http://quant.stackexchange.com/questions/22208/portfolio-optimization-with-equal-weight-for-assets-selected – JB17

+0

這個問題似乎是由於對投注結果的限制,'cov(df) '傾向於單數或幾乎單數。對df的約束包括將值限制爲0或1,要求沒有兩列相等,並且顯然0的數量應該與1的數量大致相同。你可以嘗試通過比列更多的行來避免這種情況。例如,如果通過設置'df < - df [,2:9]'只使用列X2到X9',那麼optimize.portfolio應該給你一個結果。一般來說,行數與列數之比越大越好。 – WaltS

+0

感謝您提供此信息。更大的數據幀有1000列和500行,所以我會做出調整 – JB17