| Overall Statistics |
|
Total Trades 871 Average Win 0.25% Average Loss -0.03% Compounding Annual Return 7.420% Drawdown 2.600% Expectancy 0.541 Net Profit 5.472% Sharpe Ratio 1.538 Probabilistic Sharpe Ratio 66.551% Loss Rate 85% Win Rate 15% Profit-Loss Ratio 8.97 Alpha 0.078 Beta -0.02 Annual Standard Deviation 0.049 Annual Variance 0.002 Information Ratio -0.092 Tracking Error 0.175 Treynor Ratio -3.803 Total Fees $1248.85 Estimated Strategy Capacity $3100000.00 |
from datetime import timedelta, datetime
class SMAPairsTrading(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)
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 bars of history data for each symbol in the pair and save to the variable history
history = ...
#2. Unstack the Pandas data frame to reduce it to the history close price
history = ...
#3. Iterate through the history tuple and update the mean and standard deviation with historical data