| Overall Statistics |
|
Total Trades 19 Average Win 0.16% Average Loss -0.04% Compounding Annual Return 4015.458% Drawdown 2.900% Expectancy 0.624 Net Profit 4.158% Sharpe Ratio 106.961 Probabilistic Sharpe Ratio 88.384% Loss Rate 67% Win Rate 33% Profit-Loss Ratio 3.87 Alpha 10.452 Beta 2.441 Annual Standard Deviation 0.114 Annual Variance 0.013 Information Ratio 130.066 Tracking Error 0.088 Treynor Ratio 4.999 Total Fees $24.91 Estimated Strategy Capacity $8600000.00 Lowest Capacity Asset SMH V2LT3QH97TYD |
class LiquidUniverseSelection(QCAlgorithm):
#self.lastDay = -1
filteredByPrice = None
changes = None
#self.FirstDay = 0
def SellAll(self):
#self.MarkerOnCloseOrder.Liquidate()
if self.FirstDay > 0:
self.Liquidate()
self.FirstDay = 0
self.FirstDay = self.FirstDay + 1
self.Debug(f"self.LastDay = {self.FirstDay} sstop")
self.Liquidate()
"""
def OnEndOfDay(self):
self.Debug(f"self.LastDay = {self.FirstDay} sstop")
if self.FirstDay > 0:
self.Liquidate()
self.FirstDay = 0
self.FirstDay = self.FirstDay + 1
# close up shop each day and reset our 'last' value so we start tomorrow fresh
#self.Liquidate()
#self.__last = None
"""
def __init__(self):
self.FirstDay = 0
#self.lastDay = -1
#self.mom = []
self.SetWarmUp(10, Resolution.Daily)
self.SetSecurityInitializer(lambda x: x.SetMarketPrice(self.GetLastKnownPrice(x)))
#self.SetExecution(ImmediateExecutionModel())
def Initialize(self):
self.SetStartDate(2019, 1, 8)
self.SetEndDate(2019, 1, 12)
self.SetCash(100000)
self.AddUniverse(self.CoarseSelectionFilter)
self.SetAlpha(MOMAlphaModel())
#self.SetPortfolioConstruction(InsightWeightingPortfolioConstructionModel())
self.SetPortfolioConstruction( UnEqualWeightingPortfolioConstructionModel() )
self.SetExecution(AndreExecutionModel())
#self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(23, 59), Action(self.SellAll))
#self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(10, 30), Action(self.BuyStop))
#if (Time.TimeOfDay.TotalHours > 15.9)
#self.OnEndOfDay(Action(self.SellAll))
#self.SetPortfolioConstruction()
def CoarseSelectionFilter(self, coarse):
#EquityCountCoarseSelectionFilter = 0
#self.Debug(f"EquityStartCountCoarseSelectionFilter = {EquityCountCoarseSelectionFilter}")
for cf in coarse:
symbol = cf.Symbol
#EquityCountCoarseSelectionFilter = EquityCountCoarseSelectionFilter + 1
#self.Debug(f"EquityEndCountCoarseSelectionFilter = {EquityCountCoarseSelectionFilter}")
#1. Sort descending by daily dollar volume
self.sortedByDollarVolume = sorted(coarse, key=lambda c: c.DollarVolume, reverse=True)
#2. Select only Symbols
self.symbols_by_price = [c.Symbol for c in self.sortedByDollarVolume if c.Price > 10]
#3. Return the 100 (3 for now) most liquid Symbols from the filteredByPrice list
if len(self.symbols_by_price) < 100:
self.Top100 = self.symbols_by_price[:len(self.symbols_by_price)]
else:
self.Top100 = self.symbols_by_price[:100]
#self.Debug(f"NumberOfEquitiesInTop100 = {len(self.Top100)}")
#self.Debug(f"TopOneInTop100 = {self.Top100[0]}")
#self.Debug(f"TopOneInTop100 = {self.Top100[0]}")
#self.Debug(f"BottemOneInTop100 = {self.Top100[-1]}")
#self.Debug(f"OnUpdate({self.Time}:: ","ordered (sorted_mom=)",ordered)
return self.Top100
"""
from datetime import timedelta
"""
class MOMAlphaModel(AlphaModel):
#self.lastDay = -1
def __init__(self):
self.mom = {}
self.lastDay = -1
#self.DailyMovingAverage
def OnSecuritiesChanged(self, algorithm, changes):
for security in changes.AddedSecurities:
symbol = security.Symbol
#algorithm.Debug(f"symbol= {symbol}")
self.last_return = 0
self.history = algorithm.History([symbol], 1, Resolution.Daily)
if self.history.empty:
return
algorithm.Debug(f"history.head(1)= {self.history.head(1)} stop_history")
#algorithm.Debug("time=",self.Time)
if self.history.iloc[0]["close"]:
self.last_close = self.history.iloc[0]["close"]
else: self.last_close = 1
#algorithm.Debug(f"self.last_close= {self.last_close} last_close_stop")
if self.history.iloc[0]["open"]:
self.last_open = self.history.iloc[0]["open"]
else: self.last_open = 1
#algorithm.Debug(f"self.last_open= {self.last_open} last_open_stop")
self.last_return = (self.last_close - self.last_open) / self.last_open
#algorithm.Debug(f"self.last_return= {self.last_return} last_return_stop")
#algorithm.Debug(f"self.last_close= {self.last_close} last_close_stop")
self.mom[symbol] = self.last_return
algorithm.Debug(f"self.mom[{symbol}]= {self.mom[symbol]} self.mom_stop")
for security in changes.RemovedSecurities:
symbol = security.Symbol
self.mom.pop(symbol, None)
algorithm.Debug(f"popped= {symbol}")
pass
"""
def OnData(self,data):
for symbol in self.Data.keys():
symbolData = self.Data[symbol]
if symbolData.IsReady() and symbolData.WasJustUpdated(self.Time):
# print the SMA value for each symbol
self.Log(str(symbol) + " SMA " + str(symbolData))
"""
def Update(self, algorithm, data):
if algorithm.Time.day == self.lastDay:
return []
self.lastDay = algorithm.Time.day
symbols = self.mom.keys()
#ordered = sorted(self.mom, key=lambda kv: self.mom[kv], reverse=True)
#algorithm.Debug(f"symbols[0]= {symbols[0]} stop_symbols")
self.groep =[]
self.total_weight=0
for symbol in symbols:
#self.history = algorithm.History([symbol], 1, Resolution.Daily)
self.last_return = 0
#algorithm.Debug(f"update_symbol= {symbol}_stop_update_symbol")
self.history = algorithm.History([symbol], 1, Resolution.Daily)
#algorithm.Debug(f"history.head(2)= {self.history.head(2)} update_stop_history")
if self.history.empty:
return
if self.history.iloc[0]["close"]:
# pass
self.last_close = self.history.iloc[0]["close"]
else: self.last_close = 1
#algorithm.Debug(f"self.last_close= {self.last_close} last_close_stop_update")
if self.history.iloc[0]["open"]:
self.last_open = self.history.iloc[0]["open"]
else: self.Last_open = 1
#algorithm.Debug(f"self.last_open= {self.last_open} last_open_stop")
self.last_return = (self.last_close - self.last_open) / self.last_open
#algorithm.Debug(f"self.last_return= {self.last_return} _update_last_return_stop")
#algorithm.Debug(f"self.last_close= {self.last_close} last_close_stop")
self.mom[symbol] = self.last_return
#algorithm.Debug(f"self.mom[{symbol}]= {self.mom[symbol]} self.mom_stop")
direction = InsightDirection.Flat
magnitude = self.last_return
algorithm.Debug(f"magnitude= {magnitude} stop_magnitude")
if magnitude > 0.00001:
direction = InsightDirection.Up
algorithm.Debug(f"Up Up {direction} stop up")
if magnitude < -0.00001: direction = InsightDirection.Down
#alpha_magnitude = InsightWeight.magnitude
#insights.append(Insight.Price(symbol, timedelta(1), direction, magnitude, None))
self.total_weight = self.total_weight + magnitude
#insight = Insight.Price("IBM", timedelta(minutes = 20), InsightDirection.Up, None, None, None, 0.25)
visie=Insight.Price(symbol, timedelta(minutes = 2040), direction, None, None, None, magnitude)
#algorithm.Debug(f"visie= {visie} stop_visie")
#algorithm.Debug(f"slpha_magnitude= {alpha_magnitude} stop_alpha_magnitude")
self.groep.append(visie)
#algorithm.Debug(f"Insight.Groep= {self.groep} stop_insight_groep")
return Insight.Group(self.groep)
#self.SetPortfolioConstruction( UnEqualWeightingPortfolioConstructionModel() )
#self.SetExecution(AndreExecutionModel())
class AndreExecutionModel(ExecutionModel):
def __init__(self):
'''Initializes a new instance of the ImmediateExecutionModel class'''
self.targetsCollection = PortfolioTargetCollection()
self.lastDay = -1
def Execute(self, algorithm, targets):
'''Immediately submits orders for the specified portfolio targets.
Args:
algorithm: The algorithm instance
targets: The portfolio targets to be ordered'''
if algorithm.Time.day == self.lastDay:
return []
self.lastDay = algorithm.Time.day
# for performance we check count value, OrderByMarginImpact and ClearFulfilled are expensive to call
self.targetsCollection.AddRange(targets)
if self.targetsCollection.Count > 0:
for target in self.targetsCollection.OrderByMarginImpact(algorithm):
# calculate remaining quantity to be ordered
quantity = OrderSizing.GetUnorderedQuantity(algorithm, target)
if quantity != 0:
#self.MarketOnOpenOrder("IBM", 100)
algorithm.MarketOnOpenOrder(target.Symbol, quantity)
algorithm.MarketOnCloseOrder(target.Symbol, -quantity)
self.targetsCollection.ClearFulfilled(algorithm)
#algorithm.MarketOnCloseOrder.Liquidate()
pass
class UnEqualWeightingPortfolioConstructionModel(PortfolioConstructionModel):
def __init__(self):
self.targets = []
def CreateTargets(self, algorithm, insights):
#target = PortfolioTarget.Percent(algorithm, "IBM", 0.1)
total_weight = 0
for insight in insights:
total_weight = total_weight + insight.Weight
for insight in insights:
algorithm.Debug(f"insight= {insight} stop insight.")
algorithm.Debug(f"insight.Symbol= {insight.Symbol} stop insight.Symbol.")
algorithm.Debug(f"insight.Direction= {insight.Direction} stop insight.Direction.")
algorithm.Debug(f"insight.Weight= {insight.Weight} stop insight.Weight.")
#target = PortfolioTarget.Percent(algorithm, "IBM")
target_weight = insight.Weight / total_weight
algorithm.Debug(f"target_weight= {target_weight} stop target_weight.")
target = PortfolioTarget.Percent(algorithm, insight.Symbol, target_weight)
if target_weight > 0.05:
self.targets.append(target)
return self.targets
#pass
"""
tiepe = type(symbol)
algorithm.Debug(f"type= {tiepe} stop_type")
self.history = algorithm.History([symbol], 2, Resolution.Daily)
algorithm.Debug(f"history_update= {self.history} stop_history_update")
self.history = algorithm.History([symbol], 2, Resolution.Daily)
closewaarde = self.history.iloc[0]["close"]
algorithm.Debug(f"symbol_in_update= {closewaarde} update_stop")
symbolData = data[symbol]
algorithm.Debug(f"symbolData_in_update= {symbolData} stop_symbolData")
algorithm.Debug(f"data = {data} data_stop")
"""