Hello,
I'm trying to run an algorithm that optimizes a portfolio of pre-selected assets using they diversification ratio. I want it to rebalance on the first day of each month at noon.
import numpy as np
import pandas as pd
from scipy.optimize import minimize
def diverse_ratio(weights, covariance):
# Standard deviation vector
stds = np.sqrt(np.diagonal(covariance))
# Asset-weighted standard deviation
num = np.dot(weights, stds)
# Portfolio standard deviation
denom = np.sqrt(weights @ covariance @ weights)
return num / denom
class QuantumParticleFlange(QCAlgorithm):
def Initialize(self):
self.SetCash(100000)
self.SetStartDate(2010, 1, 1)
tickers = ['VGSH',
'VGIT',
'VGLT',
'TIP',
'VMBS',
'SUB',
'VCSH',
'VCIT',
'VCLT',
'HYG',
'EMB',
'IGOV',
'VV',
'VO',
'VB',
'VWO',
'VEA',
'IYR',
'IFGL']
for ticker in tickers:
self.AddEquity(ticker, Resolution.Minute)
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
self.last_month = -1
def OnData(self, slice):
if self.Time.month == self.last_month:
return
else:
self.last_month = self.Time.month
if self.Time.hour != 12:
return
history = self.History(self.Securities.Keys, 252, Resolution.Daily)
history = history['close'].unstack(level=0).dropna()
returns = np.log(history) - np.log(history.shift(1))
returns = returns.dropna()
cov = np.cov(returns.values.T)
# Long-only constraint
bounds = [(-1, 1) for x in range(len(cov))]
# Portfolio weights must sum to 1
constraints = (
{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}
)
# Set initial weights randomly
initial = np.random.random(len(cov))
# Use negative of objective function to maximize
result = minimize(lambda x, y: -1 * diverse_ratio(x, y), initial, method='SLSQP', args=(cov),
bounds=bounds, constraints=constraints, options={'ftol': 1e-10})
weights_series = pd.Series(data=np.round(result.x, 2), index=returns.columns)
targets = []
for ticker, weight in weights_series.iteritems():
targets.append(PortfolioTarget(ticker, weight))
self.SetHoldings(targets)
This is what I have. The problem is it doesn't do anything. Running the debugger, I get this on the first iteration:
Every other iteration, however, I get this:
Every value in the alogrithm datetime object except month and day stop working and return zero. The slice object is also empty. Help?
ErikDains
Never mind, just figured it out. Because I was checking for the time after checking for the month, it never got to anything past the first minute bar of each first day of each month. Putting the check for the hour before the check for the month fixed it.
ErikDains
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!