from datetime import timedelta from QuantConnect.Data.UniverseSelection import * from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel class UglyAsparagusSheep(QCAlgorithm): def Initialize(self): self.SetStartDate(2019, 1, 1) self.SetEndDate(2020, 5, 1) self.SetCash(100000) self.SetWarmUp(200) self.UniverseSettings.Resolution = Resolution.Daily self.UniverseSettings.Leverage = self.GetParameter('Leverage') self.AddUniverseSelection(LiquidValueUniverseSelectionModel()) self.AddAlpha(LongShortEYAlphaModel()) self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel()) self.SetExecution(ImmediateExecutionModel()) self.AddEquity("IWM", Resolution.Daily) self.AddEquity("SPY", Resolution.Daily) class LiquidValueUniverseSelectionModel(FundamentalUniverseSelectionModel): def __init__(self): super().__init__(True, None, None) self.lastChange = None def SelectCoarse(self, algorithm, coarse): if self.lastChange == algorithm.Time.day: return Universe.Unchanged self.lastChange = algorithm.Time.day sortedByDollarVolume = sorted([x for x in coarse if x.HasFundamentalData], key=lambda x: x.DollarVolume, reverse=True) return [x.Symbol for x in sortedByDollarVolume[:2000]] def SelectFine(self, algorithm, fine): sortedByYields = sorted(fine, key=lambda f: f.ValuationRatios.EarningYield, reverse=True) universe = sortedByYields[:10] return [f.Symbol for f in universe] class LongShortEYAlphaModel(AlphaModel): def __init__(self): self.lastChange = None self.warmedUp = False self.bearMarket = False self.hedgeSignal = False self.ema_slow = ExponentialMovingAverage("IWM", 200, Resolution.Daily) self.ema_fast = ExponentialMovingAverage("IWM", 10, Resolution.Daily) self.ema_faster = ExponentialMovingAverage("IWM", 5, Resolution.Daily) def Update(self, algorithm, data): insights = [] if not self.ema_slow.IsReady: return insights #2. If else statement to emit signals once a day if self.lastChange == algorithm.Time.day: return insights self.lastChange = algorithm.Time.day self.bearMarket = data["IWM"].Close < self.ema_slow.Current.Value self.hedgeSignal = self.bearMarket and self.ema_faster.Current.Value < self.ema_fast.Current.Value # Not using the LiquidValueUniverseSelectionModel output for testing purpose insights.append(Insight.Price("SPY", timedelta(days=2), InsightDirection.Up)) if self.hedgeSignal: insights.append(Insight.Price("IWM", timedelta(days=2), InsightDirection.Down)) return insights