Quant League is evolving into Strategies, our new home for sharing, discovering, and exploring trading strategies, with improved organization and a better overall experience. Q4-2025 will be the final Quant League.
LEAN is the open-source algorithmic trading engine powering QuantConnect.
Founded in 2012 LEAN has been built by a global community of 180+ engineers and powers more than 300+ hedge funds today.
Join Our Discord Channel
Join QuantConnect's Discord server for real-time support, where a vibrant community of traders and developers awaits to help you with any of your QuantConnect needs.
This research is under review. To publish this research attract three community upvotes.
This research is under review. To publish this research attract three community upvotes.
This discussion is a draft. Click here to publish this discusison.
Having issues using sklearn
Hi all,
I am looking to use the strategy from the tutorial section. In my approach, i was using sklearn to calculate the intercept as opposed to numpy as in the example. For some reason, I cant get it to work. I can though get it to use in the research notebook. Attaching the code to seek you help.
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.
Mohamed Arshath
153
,
Having issues attaching the backtest. Here is the code.
import numpy as np
from sklearn.linear_model import LinearRegression
class BetaAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2016, 1, 1) # Set Start Date
self.SetEndDate(2017, 1, 1) # Set End Date
self.SetCash(10000) # Set Strategy Cash
# Dow 30 companies.
self.symbols = [self.AddEquity(ticker).Symbol
for ticker in ['AAPL', 'AXP', 'BA', 'CAT', 'CSCO', 'CVX', 'DD',
'DIS', 'GE', 'GS', 'HD', 'IBM', 'INTC', 'JPM',
'KO', 'MCD', 'MMM', 'MRK', 'MSFT', 'NKE', 'PFE',
'PG', 'TRV', 'UNH', 'UTX', 'V', 'VZ', 'WMT', 'XOM'] ]
# Benchmark
self.benchmark = Symbol.Create('SPY', SecurityType.Equity, Market.USA)
# Set number days to trace back
self.lookback = 21
# Schedule Event: trigger the event at the begining of each month.
self.Schedule.On(self.DateRules.MonthStart(self.symbols[0]),
self.TimeRules.AfterMarketOpen(self.symbols[0]),
self.Rebalance)
def Rebalance(self):
# Fetch the historical data to perform the linear regression
history = self.History(
self.symbols + [self.benchmark],
self.lookback,
Resolution.Daily).close.unstack(level=0)
symbols = self.SelectSymbols(history)
# Liquidate positions that are not held by selected symbols
for holdings in self.Portfolio.Values:
symbol = holdings.Symbol
if symbol not in symbols and holdings.Invested:
self.Liquidate(symbol)
# Invest 100% in the selected symbols
for symbol in symbols:
self.SetHoldings(symbol, 1)
def SelectSymbols(self, history):
'''Select symbols with the highest intercept/alpha to the benchmark
'''
alphas = dict()
# Get the benchmark returns
benchmark = history[self.benchmark].pct_change().dropna()
# Conducts linear regression for each symbol and save the intercept/alpha
for symbol in self.symbols:
# Get the security returns
returns = history[symbol].pct_change().dropna()
benchmark = benchmark.values.reshape(-1,1)
returns = returns.values
lr = LinearRegression()
lr.fit(benchmark, returns)
intercept = lr.intercept_
alphas[symbol] = intercept
# Select symbols with the highest intercept/alpha to the benchmark
selected = sorted(alphas.items(), key=lambda x: x[1], reverse=True)[:2]
return [x[0] for x in selected]
Â
Derek Melchin
STAFF
,
Hi Mohamed,
The issues are caused by numpy syntax errors and the parameters being passed out of order to the LinearRegression function. See the attached backtest for a working solution. Also, consider reviewing our Introduction to Financial Python tutorial series as it covers numpy and pandas.
Best, Derek Melchin
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.
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!
Allocate to this Strategy
Institutional clients can contact the author and allocate capital to this strategy.
Mohamed Arshath
Having issues attaching the backtest. Here is the code.
import numpy as np from sklearn.linear_model import LinearRegression class BetaAlgorithm(QCAlgorithm): def Initialize(self): self.SetStartDate(2016, 1, 1) # Set Start Date self.SetEndDate(2017, 1, 1) # Set End Date self.SetCash(10000) # Set Strategy Cash # Dow 30 companies. self.symbols = [self.AddEquity(ticker).Symbol for ticker in ['AAPL', 'AXP', 'BA', 'CAT', 'CSCO', 'CVX', 'DD', 'DIS', 'GE', 'GS', 'HD', 'IBM', 'INTC', 'JPM', 'KO', 'MCD', 'MMM', 'MRK', 'MSFT', 'NKE', 'PFE', 'PG', 'TRV', 'UNH', 'UTX', 'V', 'VZ', 'WMT', 'XOM'] ] # Benchmark self.benchmark = Symbol.Create('SPY', SecurityType.Equity, Market.USA) # Set number days to trace back self.lookback = 21 # Schedule Event: trigger the event at the begining of each month. self.Schedule.On(self.DateRules.MonthStart(self.symbols[0]), self.TimeRules.AfterMarketOpen(self.symbols[0]), self.Rebalance) def Rebalance(self): # Fetch the historical data to perform the linear regression history = self.History( self.symbols + [self.benchmark], self.lookback, Resolution.Daily).close.unstack(level=0) symbols = self.SelectSymbols(history) # Liquidate positions that are not held by selected symbols for holdings in self.Portfolio.Values: symbol = holdings.Symbol if symbol not in symbols and holdings.Invested: self.Liquidate(symbol) # Invest 100% in the selected symbols for symbol in symbols: self.SetHoldings(symbol, 1) def SelectSymbols(self, history): '''Select symbols with the highest intercept/alpha to the benchmark ''' alphas = dict() # Get the benchmark returns benchmark = history[self.benchmark].pct_change().dropna() # Conducts linear regression for each symbol and save the intercept/alpha for symbol in self.symbols: # Get the security returns returns = history[symbol].pct_change().dropna() benchmark = benchmark.values.reshape(-1,1) returns = returns.values lr = LinearRegression() lr.fit(benchmark, returns) intercept = lr.intercept_ alphas[symbol] = intercept # Select symbols with the highest intercept/alpha to the benchmark selected = sorted(alphas.items(), key=lambda x: x[1], reverse=True)[:2] return [x[0] for x in selected]Â
Derek Melchin
Hi Mohamed,
The issues are caused by numpy syntax errors and the parameters being passed out of order to the LinearRegression function. See the attached backtest for a working solution. Also, consider reviewing our Introduction to Financial Python tutorial series as it covers numpy and pandas.
Best,
Derek Melchin
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.
Mohamed Arshath
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!