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
Derek Melchin
Hi Abhijeet,
No orders are placed because
self.ema_slow = ExponentialMovingAverage("IWM", 200, Resolution.Daily)
creates an EMA indicator, but no consolidator is added to keep it updated. As a result,
if not self.ema_slow.IsReady
is always true.
To resolve the issue, we can replace
self.ema_slow = ExponentialMovingAverage("IWM", 200, Resolution.Daily)
with
self.ema_slow = algorithm.EMA("IWM", 200, Resolution.Daily)
This is possible because IWM never leaves the universe.
See the attached backtest for reference.
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.
Abhijeet Mulye
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!