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.SetStartDate(2010, 1, 1)

tickers = ['VGSH',

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:
self.last_month = self.Time.month

if self.Time.hour != 12:

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))


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?