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
Samuel Martini Casagrande
As I could see, the algo doesn't execute the OnData function.
I tried to put a self.Debug() inside the OnData method and shows nothing. Anyone knows what happens?
Samuel Martini Casagrande
I've found the problem. I'm gonna close the thread.
Samuel Martini Casagrande
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!