Hello guys!

Sorry if it is a dumb question, but I couldn't run the attached algo.

When I try do backtest, it returns nothing... but if I change the assets to equity, for exemple, the algo works fine.

Anyone could help me to find what I doing wrong, please?

 

Thanks in advance!

from sklearn import linear_model import numpy as np import pandas as pd from scipy import stats from math import floor from datetime import timedelta class OilSpreadTrading(QCAlgorithm): def Initialize(self): self.SetTimeZone('America/Sao_Paulo') self.SetCash(50000) # Set Strategy Cash self.SetStartDate(2016, 1, 1) # Set Start Date self.SetEndDate(2019, 9, 30) # Set Start Date self.training_period = 250 self.threshold = 1. # add used assets tickers = ['BCO_USD', 'WTICO_USD'] self.assets = [] for i in tickers: self.assets.append(self.AddSecurity(SecurityType.Cfd, i, Resolution.Daily).Symbol) # data used to train de algo to generate signals for i in self.assets: i.hist_window = RollingWindow[QuoteBar](self.training_period) def OnData(self, data): if not (data.ContainsKey('BCO_USD') and data.ContainsKey('WTICO_USD')): return # add the new data to de history for sym in self.assets: sym.hist_window.Add(data[sym]) price_x = pd.Series([float(i.Close) for i in self.assets[0].hist_window], index = [i.Time for i in self.assets[0].hist_window]) #ret_x = np.log(price_x / price_x.shift(1)) price_y = pd.Series([float(i.Close) for i in self.assets[1].hist_window], index = [i.Time for i in self.assets[1].hist_window]) if len(price_x) < 250: return spread_price = self.linreg(np.log(price_x), np.log(price_y)) mean_price = np.mean(spread_price) std_price = np.std(mean_price) ratio = floor(self.Portfolio[self.assets[1]].Price / self.Portfolio[self.assets[0]].Price) if spread_price[-1] > mean_price + self.threshold * std_price: #if not self.Portfolio[self.assets[0]].Invested and not self.Portfolio[self.assets[1]].Invested: if not self.Portfolio[self.assets[0]].Quantity > 0 and not self.Portfolio[self.assets[0]].Quantity < 0: #qtd = int(self.CalculateOrderQuantity(self.assets[0], 0.2)) qtd = 10 self.Sell(self.assets[1], qtd) self.Buy(self.assets[0], floor(ratio * qtd)) elif spread_price[-1] < mean_price - self.threshold * std_price: #qtd = int(self.CalculateOrderQuantity(self.assets[0], 0.2)) qtd = 10 #if not self.Portfolio[self.assets[0]].Invested and not self.Portfolio[self.assets[1]].Invested: if not self.Portfolio[self.assets[0]].Quantity < 0 and not self.Portfolio[self.assets[0]].Quantity > 0: self.Sell(self.assets[0], qtd) self.Buy(self.assets[1], floor(ratio * qtd)) else: self.Liquidate(self.assets[0]) self.Liquidate(self.assets[1]) def linreg(self, x, y): linreg = linear_model.LinearRegression() X1 = np.column_stack([np.ones(len(x)), x]) linreg.fit(X1, y) beta = linreg.coef_[0] alfa = linreg.intercept_ spread = y - x*beta - alfa return spread