Hi I'm going through the bootcamp 10. Below is the script
# region imports
from AlgorithmImports import *
from datetime import timedelta, datetime
# endregion
class T10PairTradingwithSMA05WarmingOurPairSpread(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2018, 7, 1)
self.SetEndDate(2019, 3, 31)
self.SetCash (100000)
symbols = [Symbol.Create("PEP", SecurityType.Equity, Market.USA), Symbol.Create("KO", SecurityType.Equity, Market.USA)]
self.AddUniverseSelection(ManualUniverseSelectionModel(symbols))
self.UniverseSettings.Resolution = Resolution.Hour
self.UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw
self.AddAlpha(PairsTradingAlphaModel())
self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())
self.SetExecution(ImmediateExecutionModel())
def OnEndOfDay(self, symbol):
self.Log("Taking-a position of " + str(self.Portfolio[symbol].Quantity)+ " units of symbol " + str(symbol))
class PairsTradingAlphaModel(AlphaModel):
def __init__(self):
self.pair = [ ]
self.spreadMean = SimpleMovingAverage(500)
self.spreadStd = StandardDeviation(500)
#1. Set self.period to a 2 hour timedelta
self.period = timedelta (hours=2)
def Update(self, algorithm, data):
spread = self.pair[1].Price - self.pair[0].Price
self.spreadMean.Update(algorithm.Time, spread)
self.spreadStd.Update(algorithm.Time, spread)
upperthreshold = self.spreadMean.Current.Value + self.spreadStd.Current.Value
lowerthreshold = self.spreadMean.Current.Value - self.spreadStd.Current.Value
if spread > upperthreshold:
return Insight.Group(
[
Insight.Price(self.pair[0].Symbol, self.period, InsightDirection.Up), Insight.Price(self.pair[1].Symbol, self.period, InsightDirection.Down)
])
if spread < lowerthreshold:
return Insight.Group(
[
Insight.Price(self.pair[0].Symbol, self.period, InsightDirection.Down), Insight.Price(self.pair[1].Symbol, self.period, InsightDirection.Up)
])
return []
def OnSecuritiesChanged(self, algorithm, changes):
self.pair = [x for x in changes.AddedSecurities]
#1. Call for 500 hours of history data for each symbol in the pair and save to the variable history
history=algorithm.History([x.Symbol for x in self.pair], 500)
#2. Unstack the Pandas data frame to reduce it to the history close price
history=history.close.unstack(level=0)
#3. Iterate through the history tuple and update the mean and standard deviation with historical data
for tuple in history.itertuples():
self.spreadMean.Update(tuple[0], tuple[2]-tuple[1])
self.spreadStd.Update(tuple[0], tuple[2]-tuple[1])
In the constructor (__init__) of the “PairsTradingAlphaModel(AlphaModel)” class, it is doing simple moving average. What quantity is moving averaged? the constructor doesn't have a parameter other than “self".
Mia Alissi
In the constructor (
__init__
) of thePairsTradingAlphaModel(AlphaModel)
class, two indicators are being initialized:self.spreadMean
andself.spreadStd
. These are instances of theSimpleMovingAverage
andStandardDeviation
classes, respectively. Both are initialized with a period of 500.The
SimpleMovingAverage
class computes the simple moving average of a given series of data. In this case, it's being used to compute the moving average of the spread between the prices of two securities (a pair). The spread is calculated asself.pair[1].Price - self.pair[0].Price
.The
StandardDeviation
class computes the standard deviation of a given series of data. In this case, it's being used to compute the standard deviation of the same spread.These two indicators are updated in the
Update
method of thePairsTradingAlphaModel
class with the current spread. The moving average and standard deviation of the spread are then used to determine the upper and lower thresholds for trading.Here is the relevant code:
So, to answer your question, the quantity that is being moving averaged is the spread between the prices of the two securities in the pair.
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.
Uhahahaha
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!