Hi people, I need your help because I can't identify where is the problem of my code. I use an example code and modify the class PortfolioOptimization using cvxpy but always give an error. When I run the class PortfolioOptimization in my pc I don't have any kind of problem, but when I run the class in quantconnect always give me an error.
Douglas Stridsberg
Hey, would you be able to provide your code so we can see what you're trying to achieve? Seeing what's inside your scheduled event function (MonthStart?) at least would be helpful.
Looks like you're trying to access a non-existing element from a list or something. This usually happens when you try to access something from the incoming data slice - you should always check first if the element you're looking for exists before using it.
Dcajasn
Here is the code :
from math import ceil,floor,isnan
from datetime import datetime
import pandas as pd
import numpy as np
import cvxpy as cv
class AssetAllocationAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2016, 1, 1) #Set Start Date
self.SetEndDate(2018, 1, 1) #Set End Date
self.SetCash(100000) #Set Strategy Cash
tickers = ["IEF", "TLT", "SPY", "EFA", "EEM", "JPXN", "XLK"]
self.symbols = []
for i in tickers:
self.symbols.append(self.AddEquity(i, Resolution.Daily).Symbol)
for syl in self.symbols:
syl.window = RollingWindow[TradeBar](252)
self.Schedule.On(self.DateRules.MonthStart("SPY"), self.TimeRules.AfterMarketOpen("SPY"), Action(self.Rebalancing))
def OnData(self, data):
if data.ContainsKey("SPY"):
for syl in self.symbols:
syl.window.Add(data[syl])
def Rebalancing(self):
data = {}
for syl in self.symbols:
data[syl] = [float(i.Close) for i in syl.window]
df_price = pd.DataFrame(data,columns=data.keys())
# To order prices from oldest to latest
df_price = df_price.sort_values(by = 0, ascending = False)
# Calculating returns
daily_return = df_price.pct_change().dropna().values
if daily_return.empty == False:
a = PortfolioOptimization(daily_return, 0, len(data))
opt_weight = a.opt_portfolio()
if isnan(sum(opt_weight)): return
self.Log(str(opt_weight))
for i in range(len(data)):
self.SetHoldings(df_price.columns[i], opt_weight[i])
# equally weighted
# self.SetHoldings(self.symbols[i], 1.0/len(data))
class PortfolioOptimization(object):
import numpy as np
import pandas as pd
import cvxpy as cv
def __init__(self, df_return, risk_free_rate, num_assets):
self.daily_return = df_return
self.risk_free_rate = risk_free_rate
self.n = num_assets # numbers of risk assets in portfolio
self.mu = np.matrix(df_return.mean(axis = 0).values)
self.sigma = df_return.cov().values
def opt_portfolio(self):
w = cv.Variable((self.mu.shape[1],1))
"""
MV model Variables
"""
risk = cv.quad_form(w, self.sigma)
constraints = [cv.sum(w) == 1]
constraints.append(w >= 0)
constraints.append(w <= 0.25)
prob = cv.Problem(cv.Minimize(risk), constraints)
prob.solve()
weights = np.matrix(w.value).T
weights = weights/np.sum(weights)
weights = np.squeeze(np.array(weights))
return weights
Douglas Stridsberg
Without a line number it's hard to tell where the problem is happening. Given the key that errors is 0, I suspect it may be the following line:
self.SetHoldings(df_price.columns[i], opt_weight[i])
Are you sure df_price.columns[0] and opt_weight[0] exist?
You're going to have to do some troubleshooting in each of the places where this error could occur - i.e. where you're accessing a collection by an ID beginning with 0.
Link Liang
Hi Dany,
I believe your PortfolioOptimization class works fine, and there are two problems with your Rebalancing method:
1. By line df_price = df_price.sort_values(by = 0, ascending = False) , I believe you want to basically reverse all rows. However, the label or index are not values and I don’t think using sort_values() is a good idea here. .iloc[::-1] works just fine here. You can find more information here and here.
2. daily_return = df_price.pct_change().dropna().values gives error: “‘numpy.ndarray’ object has no attribute ‘values’“. I believe you want the 2-D table, and .values should not be necessary here.
Here is an attempt with those modifications. Hope if helps.
Dcajasn
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!