我是R的新手,遇到了包含一些代码的障碍。我从excel导入时间序列数据,如下所示(下面的缩写版本)完整数据范围是A1:O124,A1 =" DATE":
DATE MLCIA3CD ENHG185P CIBZS1PR MLCIUKVB
1 2008-01-31 0.001632 -0.000721 0.001985 -0.014482
2 2008-02-29 -0.001620 0.001907 -0.000052 0.003801
3 2008-03-31 0.000657 -0.002661 0.001405 0.021155
4 2008-04-30 0.002729 0.000291 -0.000451 -0.009227
5 2008-05-30 0.000896 0.002460 0.007613 0.002411
6 2008-06-30 0.001253 -0.000667 0.005017 0.022411
7 2008-07-31 0.000790 0.000060 0.001744 0.007149
这是我的代码 - 我为这部分代码打开了更多的库,但我在代码的其他部分使用它们。
#Commodity Strategies
rm(list=ls())
setwd(file.path("G:","R Scripts"))
library("readxl")
library("Matrix")
library("PortfolioAnalytics")
library("zoo")
library("xts")
library("tseries")
library("nloptr")
xx<-file.path("G:","Commodity Strategies Alphas.xlsx")
mreturns<-read_excel(xx,3,range="A1:O124")
mreturns<-data.frame(mreturns)
row.names(mreturns)<-levels(mreturns$date)[mreturns$date]
##Minimum Variance
init.portf.minvar<-portfolio.spec(assets=mreturns)
init.portf.minvar<-add.constraint(portfolio=init.portf.minvar,type="full_investment")
init.portf.minvar<-add.constraint(portfolio=init.portf.minvar,type="long_only")
init.portf.minvar<-add.constraint(portfolio=init.portf.minvar,type="risk",name="StdDev")
init.portf.minvar
**minvar.lo.ROI<-optimize.portfolio(R=mreturns, portfolio=init.portf.minvar,optimize_method="ROI",trace=TRUE)**
#Results
results<-data.frame(as.vector(minvar.lo.ROI$weights))
colnames(results)<-'MinVar'
我收到的三条错误消息是:
> minvar.lo.ROI<-optimize.portfolio(R=mreturns, portfolio=init.portf.minvar,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'.