Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/205.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PortfolioAnalytics-投资回报率优化。使用重新指定的月度价格进行再平衡会产生错误的结果吗?_R_Analytics_Portfolio_R Portfolioanalytics_R Optimization - Fatal编程技术网

PortfolioAnalytics-投资回报率优化。使用重新指定的月度价格进行再平衡会产生错误的结果吗?

PortfolioAnalytics-投资回报率优化。使用重新指定的月度价格进行再平衡会产生错误的结果吗?,r,analytics,portfolio,r-portfolioanalytics,r-optimization,R,Analytics,Portfolio,R Portfolioanalytics,R Optimization,希望有人能帮助我,或者经历过类似的情况,为我指出问题所在 这是我的设置(请参阅下面的可复制代码): 建立一个符号列表 通过Yahoo的FinancialInstrument获取仪器数据 从Quandl获取欧元兑美元汇率-需要身份验证令牌 将价格重新指定为投资组合的基础货币 从2004年3月31日到今天,为以货币计价的资产和重新指定的价格(此处为欧元)建立月度回报 通过重新平衡运行ROI优化 问题是: 当按月份进行再平衡时,使用重新指定价格的回报似乎会在优化中产生错误的结果(见图),因为回报并

希望有人能帮助我,或者经历过类似的情况,为我指出问题所在

这是我的设置(请参阅下面的可复制代码):

  • 建立一个符号列表
  • 通过Yahoo的FinancialInstrument获取仪器数据
  • 从Quandl获取欧元兑美元汇率-需要身份验证令牌
  • 将价格重新指定为投资组合的基础货币
  • 从2004年3月31日到今天,为以货币计价的资产和重新指定的价格(此处为欧元)建立月度回报
  • 通过重新平衡运行ROI优化
问题是:

当按月份进行再平衡时,使用重新指定价格的回报似乎会在优化中产生错误的结果(见图),因为回报并不保证这样的回报曲线,因为投资组合的大部分投资于“TLT”-20年期国债

这将产生优化结果,如下图所示:


这是一个更大系统的一部分,但我希望我创建了一个可复制的代码,该代码显示了似乎仅在使用再平衡时才适用的问题,这向我表明,
索引
或日期可能存在问题。然而,当将两个返回XT导出到Excel时,我看不到任何差异

我在代码末尾添加了多个图表,因为我现在不能发布两张以上的图片

非常感谢任何帮助或提示,告诉我发生了什么

packages <- c('quantmod', 'FinancialInstrument', 'PortfolioAnalytics', 'Quandl')

for(i in 1:length(packages))
  library(packages[i], character.only = TRUE, quietly = TRUE)

.baseOptions <- list()
# set base CCY
.baseOptions$portf$portfolio.base.ccy <- "EUR"

# set date from which the analysis should be started
.baseOptions$portf$analyse.from <- "2004-03-31/"

# set symbols
symbol.list <- c("LQD", #iShares Investment Grade Corporate Bonds
                 "SHY", #iShares 1-3 year TBonds
                 "IEF", #iShares 3-7 year TBonds
                 "TLT" #iShares 20+ year Bonds
)

# get symbols while adjusting to dividends & splits
getSymbols(symbol.list, auto.assign = TRUE, from = "1990-01-01", to = as.character(Sys.Date()), adjust = TRUE)

# set CCY
currency(c("USD", "EUR"))

# set exchange_rate
exchange_rate("EURUSD")

# get exchange_rate
EURUSD <- Quandl('ECB/EURUSD', type = "xts", collapse = "daily", order = "asc")

stock(symbol.list, currency = "USD")

# get Fininstrument Data
update_instruments.yahoo(symbol.list)
#View(instrument.table(ls_instruments()))

# build price xts - usually part of larger sytem with different CCY incl. JPY, GBP, USD, HKD etc. 
asset.CCY.prices <- foreach(i=1:length(symbol.list), .combine = 'cbind', .packages=c('quantmod')) %dopar% {
  asset.CCY.prices <- Cl(get(symbol.list[i]))
}

# set to analysis period & monthly
asset.CCY.prices <- asset.CCY.prices[endpoints(asset.CCY.prices, on = "months")][.baseOptions$portf$analyse.from]

# redenominate to EUR
base.CCY.prices <- foreach (i=1:length(colnames(asset.CCY.prices)), .combine = 'cbind', .packages=c('FinancialInstrument')) %dopar% {

  current.instrument <- gsub(".Close", "", colnames(asset.CCY.prices)[i])
  current.instrument.CCY <- getInstrument(gsub(".Close", "", colnames(asset.CCY.prices)[i]))$currency

  if(current.instrument.CCY != .baseOptions$portf$portfolio.base.ccy)
    base.CCY.prices <- redenominate(asset.CCY.prices[,i], 
                                    new_base = .baseOptions$portf$portfolio.base.ccy, 
                                    old_base = current.instrument.CCY) 
}
rm(current.instrument, current.instrument.CCY, i, packages)
# set the colnames in the basee.CCY price .xts
colnames(base.CCY.prices) <- colnames(asset.CCY.prices) # unlist(lapply(symbol.list, function(x) paste(x, .baseOptions$portf$portfolio.base.ccy, sep = ".")))

# build returns
asset.CCY.R <- ROC(asset.CCY.prices)
base.CCY.R <- ROC(base.CCY.prices)

# portfolio optimization
#
#
#-----------------------------------
# Specify initial portfolio
if(exists("portf.init")) rm(portf.init)
portf.init <- portfolio.spec(assets=colnames(asset.CCY.R))
portf.init <- add.constraint(portfolio=portf.init, type="weight_sum", min_sum=0.99, max_sum=1.01)
portf.init <- add.constraint(portfolio=portf.init, type="long_only")
#portf.init <- add.constraint(portfolio=portf.init, type="position_limit", max_pos=15)

#' Add objective to maximize mean
portf.init <- add.objective(portfolio=portf.init, type="return", name="mean")

#----------------------------------
# Global Minimum Variance Portfolio
# 
if(exists("GMV")) rm(GMV)
GMV <- add.constraint(portfolio=portf.init, type="weight_sum", min_sum=0.90, max_sum=1.01, indexnum = 1) 
# Add box constraint
GMV <- add.constraint(GMV, type="box", min=0, max=0.99)
# Add var objective - risk is always minimised
GMV <- add.objective(GMV, type = "risk", name = "var")

# optimization in asset.CCY
opt.asset.CCY = optimize.portfolio.rebalancing(R = asset.CCY.R, portfolio = GMV, rebalance_on = "months", optimize_method = "ROI")
port.data.asset.CCY <- Return.portfolio(R = asset.CCY.R, weights = extractWeights(opt.asset.CCY), verbose=TRUE)

#optimization in base.CCY
opt.base.CCY = optimize.portfolio.rebalancing(R = base.CCY.R, portfolio = GMV, rebalance_on = "months", optimize_method = "ROI")
port.data.base.CCY <- Return.portfolio(R = base.CCY.R, weights = extractWeights(opt.base.CCY), verbose=TRUE)
opt.base.CCY.simple = optimize.portfolio(R = base.CCY.R, portfolio = GMV, optimize_method = "ROI")
port.data.base.CCY.simple <- Return.portfolio(R = base.CCY.R, weights = extractWeights(opt.base.CCY.simple), verbose=TRUE)


#--------- START EDIT 04.01.2016 ---------
#
class(index(asset.CCY.R))
indexTZ(asset.CCY.R)
# Indexed by Class Date - XTS though shows TZ = UTC
# this should however not cause any issues
all.equal(index(asset.CCY.R), index(base.CCY.R))
# TRUE

# Weights after rebalancing
class(index(extractWeights(opt.asset.CCY)))
# "POSIXct" "POSIXt" which should be fine as well
all.equal(index(extractWeights(opt.asset.CCY)), 
          index(extractWeights(opt.base.CCY)))
# TRUE
#
#--------- END EDIT 04.01.2016 ---------


# charts
#
op <- par(mfrow = c(2, 2), pty = "m") 

# chart the time series
chart.TimeSeries(asset.CCY.prices, main = 'Timeseries - Asset.CCY', legend.loc = "top")
# chart the performance summaries
chart.CumReturns(asset.CCY.R, main = "Cum Returns - Asset.CCY")
# chart the time series
chart.TimeSeries(base.CCY.prices, main = 'Base.CCY', legend.loc = "top")
# chart the performance summaries
chart.CumReturns(base.CCY.R, main = "Cum Returns - Base.CCY")

# Optimized returns - rebalancing
chart.CumReturns(port.data.asset.CCY$returns, main=paste("Asset.CCY", "Opt Return" , sep= " - "))
chart.CumReturns(port.data.base.CCY$returns, main=paste("Base.CCY", "Opt Return" , sep= " - "))

# Optimized returns - no rebalancing
chart.CumReturns(port.data.base.CCY.simple$returns, main=paste("Base.CCY.simple", "Opt Return" , sep= " - "))

# optimizes EOP Value Charts
chart.StackedBar(port.data.asset.CCY$EOP.Value[ , !apply(port.data.asset.CCY$EOP.Value==0,2,all)], main=paste("Asset.CCY", "Value" , sep= " - "))
chart.StackedBar(port.data.base.CCY$EOP.Value[ , !apply(port.data.base.CCY$EOP.Value==0,2,all)], main=paste("Base.CCY", "Value" , sep= " - "))

# Optimized EOP Value - no rebalancing
chart.StackedBar(port.data.base.CCY.simple$EOP.Value[ , !apply(port.data.base.CCY.simple$EOP.Value==0,2,all)], main=paste("Base.CCY.simple", "Value" , sep= " - "))

# optmized Contribution charts
chart.StackedBar(port.data.asset.CCY$contribution[ , !apply(port.data.asset.CCY$contribution==0,2,all)], main=paste("Asset.CCY", "Contribution" , sep= " - "))
chart.StackedBar(port.data.base.CCY$contribution[ , !apply(port.data.base.CCY$contribution==0,2,all)], main=paste("Base.CCY", "Contribution" , sep= " - "))

# optmized Contribution charts - no rebalancing
chart.StackedBar(port.data.base.CCY.simple$contribution[ , !apply(port.data.base.CCY.simple$contribution==0,2,all)], main=paste("Base.CCY.simple", "Contribution" , sep= " - "))

# restore usual charting
par(op)

sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8 x64 (build 9200)

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252    LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C                            LC_TIME=English_United Kingdom.1252    

attached base packages:
[1] parallel  stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] PortfolioAnalytics_1.0.3636   XML_3.98-1.3                  FinancialInstrument_1.2.0     RColorBrewer_1.1-2           
 [5] reshape2_1.4.1                doParallel_1.0.10             iterators_1.0.8               rCharts_0.4.5                
 [9] RcppDE_0.1.4                  timeDate_3012.100             sqldf_0.4-10                  RSQLite_1.0.0                
[13] DBI_0.3.1                     gsubfn_0.6-6                  proto_0.3-10                  stringr_1.0.0                
[17] ggplot2_1.0.1                 xlsx_0.5.7                    xlsxjars_0.6.1                rJava_0.9-7                  
[21] quantmod_0.4-5                TTR_0.23-0                    Quandl_2.7.0                  ProjectTemplate_0.6          
[25] PerformanceAnalytics_1.4.3541 foreach_1.4.3                 xts_0.9-7                     zoo_1.7-12
根据As.Date的帮助页面,这假设“POSIXct”为“UTC”,因此我假设存在差异,但以下也返回第29个:

as.Date(first(index(weights), tz = "Europe/Berlin"))
# [1] "2007-03-29"
这对我来说并不清楚,但对于重量xts来说是一致的,而不是这个问题的一部分

在第72行return.portfolio中,现在通过执行以下操作将return xts减少到相同的起始索引:

R <- R[paste0(as.Date(index(weights[1, ])) + 1, "/")]
编辑2016年1月6日

在进一步研究Return.portfolio()调用的PerformanceAnytics包中Return.portfolio.geometric()的代码之后:

  • 迭代与收益计算
  • 第49行:

    ret[k] = eop_value_total[k]/end_value - 1 
    
    这将计算投资组合回报,在本例中,它将为0.877/1-1,这显然将导致-12.3%的回报

    如果我看得对,这意味着如果在Return.portfolio()调用期间用户没有在value设置中提供权重,则期望权重等于end_值的100%,设置为1或100%

    下一次迭代的结束_值为0.877

    end_value = eop_value_total[k]
    
  • 迭代和返回计算
  • 下一期的新投资组合起始值0.877乘以下一期权重90%或0.90=0.7893

    bop_value[k, ] = end_value * weights[i, ]
    
    与第一次迭代相同,由于权重和约束,PortfolioAnalytics包计算的总权重为90%,因此负回报将再次被夸大

    ret[k] = eop_value_total[k]/end_value - 1
    
    转化为0.78/0.877-1=-0.111

    那么,我想到的问题是:

    • 当权重为100%或1时,如何计算正确的回报
    • 100%的权重和约束真的有意义吗?在现实生活中,缺少的%可能是现金/短期债券
    • 基于此-选项可以是在使用完全投资约束的同时将现金回报添加到优化中,或者,调整几何回报函数以警告权重为100%或包含权重为100%的逻辑,这不是一个选项吗
    最后但并非最不重要的一点,或者我的日期索引仍然有问题

    不确定是否有人还在读这篇文章,但再次强调,如果有人支持或洞察,我们将不胜感激。非常感谢

    bop_value[k, ] = end_value * weights[i, ]
    
    ret[k] = eop_value_total[k]/end_value - 1