Overall Statistics |
Total Trades 0 Average Win 0% Average Loss 0% Compounding Annual Return 0% Drawdown 0% Expectancy 0 Net Profit 0% Sharpe Ratio 0 Probabilistic Sharpe Ratio 0% Loss Rate 0% Win Rate 0% Profit-Loss Ratio 0 Alpha 0 Beta 0 Annual Standard Deviation 0 Annual Variance 0 Information Ratio -3.291 Tracking Error 0.166 Treynor Ratio 0 Total Fees $0.00 |
from MovingReturn import MovRet import numpy as np from datetime import datetime, timedelta class DynamicOptimizedContainmentField(QCAlgorithm): def Initialize(self): self.SetStartDate(2020,10,1) #Set Start Date # self.SetEndDate(2020,10,15) #Set End Date self.SetCash(50000) #Set Strategy Cash self.UniverseSettings.Resolution = Resolution.Daily # self.SetSecurityInitializer(self.CustomSecurityInitializer) self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage) self.AddUniverse(self.CoarseSelectionFilter) self.Data = {} self.symbols=[] self.symbols_fine=[] self.stateData={} # self.EnableAutomaticIndicatorWarmUp = True self.N=10 def CoarseSelectionFilter(self, coarse): sortedByDollarVolume = sorted(coarse, key=lambda c: c.DollarVolume, reverse=True) filteredByPrice = [c.Symbol for c in sortedByDollarVolume if c.Price > 10] return filteredByPrice[:2] def MyCoarseFilterFunction(self, coarse): d = self.Time.date() if d.weekday() == 4 : # We are going to use a dictionary to refer the object that will keep the moving averages for c in coarse: if c.Symbol not in self.stateData: self.stateData[c.Symbol] = SelectionData(c.Symbol, 200,100,10) # history = self.History(c.Symbol, 201) # for tuple in history.loc[c.Symbol].itertuples(): # self.stateData[c.Symbol].update(tuple.Index,tuple.close,tuple.volume) # # Updates the SymbolData object with current EOD price avg = self.stateData[c.Symbol] avg.update(c.EndTime, c.AdjustedPrice, c.DollarVolume) # Take top 500 highest 200 period volume EMA. sortedByDollarVolume = sorted(self.stateData.values(), key=lambda x: x.smaVol, reverse=True)[:500] # Filter the values of the dict to those that have a weekly RSI<20 values = [x for x in sortedByDollarVolume if x.belowRSI ] # Filter the least volatiles stocks values.sort(key=lambda x: x.volatility, reverse=False) # Take 10 smallest volatility stocks self.symbols= [ x.symbol for x in values[:10] ] return self.symbols else: return self.symbols def SelectFine(self, fine): d = self.Time.date() if d.weekday() == 4: sortedByMarketPlace = sorted([x for x in fine if x.CompanyReference.PrimaryExchangeID in ["NYS","NAS"]], key = lambda x: x.CompanyReference.IndustryTemplateCode) self.symbols_fine = [x.Symbol for x in sortedByMarketPlace] return self.symbols_fine else : return self.symbols_fine def OnSecuritiesChanged(self,changes): for removed in changes.RemovedSecurities: symbolData = self.Data.pop(removed.Symbol, None) # initialize data for added securities for security in changes.AddedSecurities: symbol = security.Symbol if symbol not in self.Data: self.Data[symbol] = SymbolData(self,symbol) def OnData(self,data): d = self.Time.date() invested = [x.Key for x in self.Portfolio if x.Value.Invested] Nb_invested = len(invested) available_space = self.N - Nb_invested symbol = list(self.Data.keys())[0] symbolData=self.Data[symbol] Close_Window=symbolData.Close_window U=[] D=[] for i in range(5,Close_Window.Count+1,5): #5,10,15 if Close_Window[i]-Close_Window[i-5] >0: U.append(Close_Window[i]-Close_Window[i-5]) else : U.append(0) if Close_Window[i]-Close_Window[i-5] <0: D.append(np.abs(Close_Window[i]-Close_Window[i-5])) else : D.append(0) AvgU=np.mean(U) AvgD=np.mean(D) RS=AvgU/AvgD RSI=100-100.0/(1+RS) self.Debug(RSI) # for symbol in list(self.Data.keys()): # if not data.ContainsKey(symbol): #Tested and Valid/Necessary # return # invested = [x.Key for x in self.Portfolio if x.Value.Invested] # Nb_invested = len(invested) # if self.Securities[symbol].Invested is False and Nb_invested <= 10 and d.weekday() == 4 : # self.SetHoldings(symbol, 1/self.N) # if self.Securities[symbol].Invested: # # if len(self.Transactions.GetOpenOrders(symbol)) is 0 : # self.StopMarketOrder(symbol, -self.Portfolio[symbol].Quantity, 0.9 * self.Securities[symbol].Close) # self.Debug(len(self.Transactions.GetOpenOrders(symbol))) # if symbolData.RSI.Current.Value>80 and d.weekday() == 4: # self.Liquidate(symbol) class SelectionData(object): def __init__(self, symbol, periodSMAVolume,periodVol,periodRSI): self.symbol = symbol self.smaVol = SimpleMovingAverage(periodSMAVolume) self.belowRSI=False self.volatility=SimpleMovingAverage(periodVol) self.volume=0 self.Close=0 self.Time=None self.RSI = RelativeStrengthIndex(periodRSI) def update(self, time, price, volume): self.volume=volume self.smaVol.Update(time,volume) #update volume and belowRSI boolean self.volatility.Update(time,np.std(price)) self.Time=time self.Close=price self.RSI.Update(time, price) self.belowRSI= self.RSI.Current.Value < 20 class SymbolData: def __init__(self, algorithm, symbol): self.algorithm = algorithm self.symbol = symbol self.Close_window=RollingWindow[float](5*3) self.IsReady=False self.Time=None def OnDataConsolidated(self, sender, bar): self.Close_window.Add(bar.Close) self.IsReady = self.RSI.IsReady self.Time=bar.Time
import numpy as np from collections import deque from datetime import datetime, timedelta from array import * from MovingReturn import MovRet class BasicTemplateAlgorithm(QCAlgorithm): '''Basic template algorithm simply initializes the date range and cash''' def Initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.SetStartDate(2004,11,8) #Set Start Date self.SetEndDate(2004,12,30) #Set End Date self.SetCash(50000) #Set Strategy Cash self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage) # self.SetSecurityInitializer(self.CustomSecurityInitializer) # self.UniverseSettings.Resolution = Resolution.Daily # self.AddUniverse(self.MyCoarseFilterFunction,self.SelectFine) self.stateData = { } self.Stocks_to_Buy=[] self.__numberOfSymbols = 4 self.changes = None # self.Schedule.On(self.DateRules.EveryDay(),self.TimeRules.At(12, 0),self.rebalance) self.weekly_rebalance = False self.SetWarmup(2) self.rsi=[] self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol # self.M126=MovRet(2) # self.RegisterIndicator(self.spy, self.M126, Resolution.Daily) def MyCoarseFilterFunction(self, coarse): # We are going to use a dictionary to refer the object that will keep the moving averages for c in coarse: if c.Symbol not in self.stateData: self.stateData[c.Symbol] = SelectionData(c.Symbol, 2,2,1) # Updates the SymbolData object with current EOD price avg = self.stateData[c.Symbol] avg.update(c.EndTime, c.AdjustedPrice, c.DollarVolume,self.weekly_rebalance) # Take top 500 highest 200 period volume EMA. sortedByDollarVolume = sorted(self.stateData.values(), key=lambda x: x.smaVol, reverse=True)[:500] # Filter the values of the dict to those that have a weekly RSI<20 values = [x for x in sortedByDollarVolume if x.belowRSI ] # Filter the least volatiles stocks values.sort(key=lambda x: x.volatility, reverse=False) # Take 10 smallest volatility stocks return [ x.symbol for x in values[:self.__numberOfSymbols] ] # def SelectFine(self, fine): # sortedByMarketPlace = sorted([x for x in fine if x.CompanyReference.PrimaryExchangeID in ["NYS","NAS"]], key = lambda x: x.CompanyReference.IndustryTemplateCode) # return [x.Symbol for x in sortedByMarketPlace] def OnData(self,data): # if self.changes is None: return # for security in self.changes.AddedSecurities: # if not security.Invested: # self.Stocks_to_Buy.append(security.Symbol) # for security in self.Stocks_to_Buy: # self.Debug("{} Buy {}".format(self.Time, security.Value)) # self.SetHoldings(security, 1.0/len(self.Stocks_to_Buy)) self.SetHoldings(spy,1) # if security.Invested: # self.StopMarketOrder(security.Symbol, -self.Portfolio[security.Symbol].Quantity, 0.9 * self.Securities[security.Symbol].Close) # self.MarketOnOpenOrder(self.shy, self.Portfolio.MarginRemaining/self.Securities["SHY"].Price) security = self.Portfolio.Values[0] self.Debug(security.Symbol) self.Debug(self.Securities[security.Symbol].Close) if security.Invested: symbol=security.Symbol self.Debug(symbol) self.rsi = self.SMA(symbol, 2, MovingAverageType.Simple, Resolution.Daily) self.RegisterIndicator(symbol, self.rsi, timedelta(days=1)) history = self.History([symbol], 2, Resolution.Daily) self.window_Close=RollingWindow[float](2) for time, row in history.loc[symbol].iterrows(): self.rsi.Update(time, row["close"]) self.window_Close.Add(row["close"]) self.Debug(self.window_Close) self.Debug(self.rsi.Current.Value) # self.Debug(symbol) # self.rsi=self.RSI(symbol,2) # if self.rsi.Current.Value>20: # self.Liquidate(symbol) # self.Debug("{} Liquidate {}".format(self.Time, symbol.Value)) # self.changes=None # def OnSecuritiesChanged(self, changes): # self.changes = changes # def OnOrderEvent(self, fill): # return # # self.Debug(f"OnOrderEvent({self.UtcTime}):: {fill}") def rebalance(self): d = self.Time.date() if d.weekday() == 3: self.weekly_rebalance = True else: self.weekly_rebalance = False class SelectionData(object): def __init__(self, symbol, periodSMAVolume,periodRSI,periodVol): self.symbol = symbol self.smaVol = SimpleMovingAverage(periodSMAVolume) self.rsi = RelativeStrengthIndex(periodRSI) self.belowRSI=False self.volatility=SimpleMovingAverage(periodVol) self.volume=0 self.weekly_rebalance=False def update(self, time, price, volume,weeklyupdate): self.volume=volume self.smaVol.Update(time,volume) #update volume and belowRSI boolean self.volatility.Update(time,np.std(price)) self.weekly_rebalance=weeklyupdate # if self.weekly_rebalance: self.rsi.Update(time,price) self.belowRSI=self.rsi.Current.Value<20
import numpy as np from collections import deque from datetime import datetime ### <summary> ### Basic template algorithm simply initializes the date range and cash. This is a skeleton ### framework you can use for designing an algorithm. ### </summary> class MovRet(): def __init__(self,periods): self.N=periods self.window = RollingWindow[float](periods) self.window_Close=RollingWindow[float](2) self.IsReady=False self.IsReadyClose=False # Volatility is a mandatory attribute self.Value = 0 self.Close=0 # Updates this model using the new price information in the specified security instance # Update is a mandatory method def Update(self,input): self.Close=input.Close self.window_Close.Add(input.Close) if self.window_Close.IsReady: self.IsReadyClose=True self.window.Add(float(self.window_Close[0] / self.window_Close[1]) - 1.0) if self.window.IsReady: self.Value=np.mean([ x for x in self.window ]) self.IsReady=self.window.IsReady if self.window.Count<self.N: self.Value=0 if self.window.Count<2: self.Value=0 self.IsReadyClose=False
class DynamicOptimizedContainmentField(QCAlgorithm): def Initialize(self): self.SetStartDate(2020, 9, 20) # Set Start Date self.SetCash(100000) # Set Strategy Cash self.UniverseSettings.Resolution = Resolution.Daily self.AddUniverse(self.SelectCoarse) self.symbols = {} self.symbolUniv=[] def SelectCoarse(self, coarse): # d = self.Time.date() # if d.weekday() == 4 : sortedCoarse = sorted(coarse, key=lambda c:c.DollarVolume, reverse=True) self.symbolUniv = [c.Symbol for c in sortedCoarse][:2] return self.symbolUniv # else : # return self.symbolUniv # def MyCoarseFilterFunction(self, coarse): # d = self.Time.date() # if d.weekday() == 4 : # # We are going to use a dictionary to refer the object that will keep the moving averages # for c in coarse: # if c.Symbol not in self.stateData: # self.stateData[c.Symbol] = SymbolData_forUniverse_daily(c.Symbol, 200,100) # # history = self.History(c.Symbol, 201) # # for tuple in history.loc[c.Symbol].itertuples(): # # self.stateData[c.Symbol].update(tuple.Index,tuple.close,tuple.volume) # # # Updates the SymbolData object with current EOD price # avg = self.stateData[c.Symbol] # avg.update(c.EndTime, c.AdjustedPrice, c.DollarVolume) # # Take top 500 highest 200 period volume EMA. # sortedByDollarVolume = sorted(self.stateData.values(), key=lambda x: x.smaVol, reverse=True)[:500] # # Filter the values of the dict to those that have a weekly RSI<20 # values = [x for x in sortedByDollarVolume if x.belowRSI ] # # Filter the least volatiles stocks # values.sort(key=lambda x: x.volatility, reverse=False) # # Take 10 smallest volatility stocks # self.symbols= [ x.symbol for x in values[:2] ] # return self.symbols def OnSecuritiesChanged(self, changes): for security in changes.AddedSecurities : symbol = security.Symbol if symbol not in self.symbols: history = self.History(symbol,14, Resolution.Daily) self.symbols[symbol] = SymbolData_forAlpha(self,symbol) if not history.empty: self.symbols[symbol].Warmup(history) for security in changes.RemovedSecurities : symbol = security.Symbol if symbol in self.symbols: symbolData = self.symbols.pop(symbol, None) def OnData(self,data): d = self.Time.date() #self.Debug(5) symbol = list(self.symbols.keys())[0] symbolData=self.symbols[symbol] #self.Debug(symbol) if symbolData.IsReady : self.Log(f"Time: {symbolData.Time}; Close: {symbolData.Close}; RSI: {symbolData.RSI.Current.Value}") class SymbolData_forAlpha: def __init__(self, algorithm, symbol): self.algorithm = algorithm self.symbol = symbol self.consolidator = TradeBarConsolidator(timedelta(days=7)) self.consolidator.DataConsolidated += self.OnDataConsolidated algorithm.SubscriptionManager.AddConsolidator(symbol, self.consolidator) self.Time=None self.Close=0 self.RSI=SimpleMovingAverage(2) self.IsReady=False self.belowRSI=False def OnDataConsolidated(self, sender, bar): self.algorithm.Log(f"Data Consolidatoed for {self.symbol} at {bar.EndTime} with bar: {bar}") #self.algorithm.Log(str(bar.Time) + " " + str(bar)) self.Close=bar.Close self.Time=bar.EndTime self.RSI.Update(self.Time, bar.Close) self.IsReady = self.RSI.IsReady def Warmup(self,history): for index, row in history.loc[str(self.symbol)].iterrows(): self.Close=row["close"] self.RSI.Update(index, row["close"]) self.Time=index # class SymbolData_forUniverse_week: # def __init__(self, algorithm, symbol,periodRSI): # self.algorithm = algorithm # self.symbol = symbol # self.consolidator = TradeBarConsolidator(timedelta(days=7)) # self.consolidator.DataConsolidated += self.OnDataConsolidated # algorithm.SubscriptionManager.AddConsolidator(symbol, self.consolidator) # self.Time=None # self.Close=0 # self.RSI=SimpleMovingAverage(periodRSI) # self.IsReady=False # self.belowRSI=False # def OnDataConsolidated(self, sender, bar): # self.Debug(str(self.Time) + " " + str(bar)) # self.algorithm.Debug(f"Data Consolidatoed for {self.symbol} at {bar.EndTime} with bar: {bar}") # self.Close=bar.Close # self.Time=bar.EndTime # self.RSI.Update(bar.Time, bar.Close) # self.IsReady = self.RSI.IsReady # self.belowRSI= self.RSI.Current.Value < 20 # class SymbolData_forUniverse_daily(object): # def __init__(self, symbol, periodSMAVolume,periodVol): # self.symbol = symbol # self.smaVol = SimpleMovingAverage(periodSMAVolume) # self.volatility=SimpleMovingAverage(periodVol) # self.volume=0 # self.Close=0 # self.Time=None # def update(self, time, price, volume): # self.volume=volume # self.smaVol.Update(time,volume) #update volume and belowRSI boolean # self.volatility.Update(time,np.std(price)) # self.Time=time # self.Close=price
from MovingReturn import MovRet import numpy as np from datetime import datetime, timedelta class DynamicOptimizedContainmentField(QCAlgorithm): def Initialize(self): self.SetStartDate(2010,1,1) #Set Start Date self.SetEndDate(2010,3,15) #Set End Date self.SetCash(50000) #Set Strategy Cash self.UniverseSettings.Resolution = Resolution.Daily self.AddUniverse(self.SelectCoarse) self.Stocks_to_Buy=[] self.Data = {} self.Data2 = {} self.Data3 = {} self.sma={} self.stateData = { } self.symbols=[] self.symbols2=[] self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol self.M126=MovRet(126) self.RegisterIndicator(self.spy, self.M126, Resolution.Daily) self.Portfolio_SD={} self.weekly_rebalance = False def SelectCoarse(self, coarse): d = self.Time.date() if d.weekday() == 4: self.weekly_rebalance = True sortedCoarse = sorted(coarse, key=lambda c:c.DollarVolume, reverse=True) self.symbols = [c.Symbol for c in sortedCoarse][:6] return self.symbols else: return self.symbols def MyCoarseFilterFunction(self, coarse): d = self.Time.date() if d.weekday() == 4: # We are going to use a dictionary to refer the object that will keep the moving averages for c in coarse: if c.Symbol not in self.stateData: self.stateData[c.Symbol] = SelectionData(c.Symbol, 2,2,1) # Updates the SymbolData object with current EOD price avg = self.stateData[c.Symbol] avg.update(c.EndTime, c.AdjustedPrice, c.DollarVolume) # Take top 500 highest 200 period volume EMA. sortedByDollarVolume = sorted(self.stateData.values(), key=lambda x: x.smaVol, reverse=True)[:500] # Filter the values of the dict to those that have a weekly RSI<20 values = [x for x in sortedByDollarVolume if x.belowRSI ] # Filter the least volatiles stocks values.sort(key=lambda x: x.volatility, reverse=False) # Take 10 smallest volatility stocks self.symbols= [ x.symbol for x in values[:10] ] return self.symbols else: return self.symbols def OnSecuritiesChanged(self, changes): for security in changes.AddedSecurities: symbol = security.Symbol if symbol not in self.Data: self.Data[symbol] = SymbolData(self, symbol) # Warm up RSI indicators history = self.History(symbol, timedelta(7)) for tuple in history.loc[symbol].itertuples(): self.Data[symbol].Close=tuple.close self.Data[symbol].RSI.Update(tuple.Index, tuple.close) self.Data[symbol].Time=tuple.Index for security in changes.RemovedSecurities: symbol = security.Symbol if symbol in self.Data: symbolData = self.Data.pop(symbol, None) self.SubscriptionManager.RemoveConsolidator(symbol, symbolData.consolidator) def OnData(self,data): d = self.Time.date() symbol = list(self.Data.keys())[0] self.Data2[symbol]=SelectionData_1(self,2,1) a=self.Data2[symbol] a.update(self.Time,data[symbol].Close,data[symbol].Volume) self.Data3[symbol]=SymbolData(self,symbol) b=self.Data3[symbol] # history = self.History(symbol, timedelta(7)) # for tuple in history.loc[symbol].itertuples(): # self.Data3[symbol].Close=(tuple.close) # # self.Data3[symbol].RSI.Update(tuple.Index, tuple.close) # self.Data3[symbol].Time=tuple.Index # self.Debug(a.Time) self.Debug(b.Time) self.Debug(b.Close) # invested = [x.Key for x in self.Portfolio if x.Value.Invested] # Nb_invested = len(invested) # for symbol in list(self.Data.keys()): # if not data.ContainsKey(symbol): #Tested and Valid/Necessary # return # symbolData = self.Data[symbol] # available_space = 9 - Nb_invested # if self.Securities[symbol].Invested is False and available_space > 0 and symbolData.IsReady and d.weekday() == 4 and self.M126.Value > 0 : # self.SetHoldings(symbol, 1.0/(available_space)) # if self.Securities[symbol].Invested: # self.StopMarketOrder(symbol, -self.Portfolio[symbol].Quantity, 0.9 * self.Securities[symbol].Close) # if symbolData.RSI.Current.Value>80 and d.weekday() == 4: # self.Liquidate(symbol) class SymbolData: #updates on Mondays def __init__(self, algorithm, symbol): self.algorithm = algorithm self.symbol = symbol self.consolidator = TradeBarConsolidator(timedelta(days=3)) self.consolidator.DataConsolidated += self.OnDataConsolidated self.Bars = RollingWindow[IBaseDataBar](1) # The simple moving average indicator for our symbol self.RSI = RelativeStrengthIndex(2) algorithm.SubscriptionManager.AddConsolidator(symbol, self.consolidator) self.Close=0 self.IsReady=False self.Time=None def OnDataConsolidated(self, sender, bar): self.RSI.Update(bar.Time, bar.Close) self.Bars.Add(bar) self.Close=bar.Close self.IsReady = self.RSI.IsReady self.Time=bar.Time class SelectionData_1(object): def __init__(self, symbol, periodSMAVolume,periodVol): self.symbol = symbol self.smaVol = SimpleMovingAverage(periodSMAVolume) self.belowRSI=False self.volatility=SimpleMovingAverage(periodVol) self.volume=0 self.Close=0 self.Time=None def update(self, time, price, volume): self.volume=volume self.smaVol.Update(time,volume) #update volume and belowRSI boolean self.volatility.Update(time,np.std(price)) self.Time=time self.Close=price class SelectionData_2: def __init__(self, algorithm, symbol,periodRSI): self.algorithm = algorithm self.symbol = symbol self.consolidator = TradeBarConsolidator(timedelta(days=2)) self.consolidator.DataConsolidated += self.OnDataConsolidated algorithm.SubscriptionManager.AddConsolidator(symbol, self.consolidator) # self.RSI = SimpleMovingAverage(periodRSI) self.Close=0 # self.Close=RollingWindow[float](1) # self.IsReady=False self.Time=None # self.belowRSI=False # self.Bars = RollingWindow[IBaseDataBar](1) def OnDataConsolidated(self, sender, bar): # self.RSI.Update(bar.Time, bar.Close) # self.Close.Add(bar.Close) # self.IsReady = self.RSI.IsReady # self.Time=bar.Time # self.belowRSI=self.RSI.Current.Value<20 self.Close=bar.Close self.Time=bar.Time # Your New Python File