Back

Adding a moving average indicator as an condition.

Hi all,

I am currently attempting to add a moving average condition to one of the excellent tutorials provided on this platform. As I am still learning, it would be very helpful for me to understand the following. I would like to improve the performance for the algo below (provided in this tutorial: Tutorials - Strategy Library - CAPM Alpha Ranking Strategy on Dow 30... by adding on and testing a simple/or exponential moving average that would serve as a condition. The idea is that the algo would only purchase the selected stocks if the DJI moving average is over 200 days for example. If the condition is not met, the algo would then simply do nothing until the condition is met. 

 

Many thanks for any help on this!

import numpy as np

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()
returns = np.vstack([returns, np.ones(len(returns))]).T

# Simple linear regression function in Numpy
result = np.linalg.lstsq(returns, benchmark)
alphas[symbol] = result[0][1]

# 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]

 

 

Update Backtest







0

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.


Hey Martin,

You can track the performance of DJI through DIA, which is an ETF which tracks the value of DJI. Then we can add an 200 day simple moving average indicator for DIA and warm it up. Learn more about indicators and warmups in the documentation. Then in the rebalance function we can add some checks that wait until the Dow Jones is over its 200 day SMA until doing something.

Check out the backtest below to see how it works.

1

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.


Update Backtest





0

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.


Loading...

This discussion is closed