| 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 Loss Rate 0% Win Rate 0% Profit-Loss Ratio 0 Alpha 0 Beta 0 Annual Standard Deviation 0 Annual Variance 0 Information Ratio 0 Tracking Error 0 Treynor Ratio 0 Total Fees $0.00 |
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Indicators")
AddReference("QuantConnect.Common")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from datetime import datetime
from Alphas.MacdAlphaModel import MacdAlphaModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
class SymbolData:
def __init__(self, symbol, algorithm):
self.Symbol = symbol
self.buypoint, self.sellpoint= None, None
self.longLiqPoint, self.shortLiqPoint, self.yesterdayclose= None, None, None
self.numdays = 30
self.Bolband = algorithm.BB(symbol, self.numdays, 2, MovingAverageType.Simple, Resolution.Daily)
self.__previous = datetime.min
class OptimizedDynamicRegulators(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2018, 10, 25) # Set Start Date
self.SetCash(100000) # Set Strategy Cash
# self.AddEquity("SPY", Resolution.Minute)
self.AddAlpha(MacdAlphaModel(12, 26, 9, MovingAverageType.Exponential, Resolution.Daily))
self.numdays = 30
self.ceiling,self.floor = 60,20
self.SetBenchmark("SPY")
self.SetExecution(ImmediateExecutionModel())
self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())
self.SetRiskManagement(MaximumSectorExposureRiskManagementModel())
self.__numberOfSymbols = 100
self.__numberOfSymbolsFine = 5
self.SetUniverseSelection(FineFundamentalUniverseSelectionModel(self.CoarseSelectionFunction, self.FineSelectionFunction, None, None))
def OnData(self,data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
# wait for our macd to fully initialize
if not self.MACD.IsReady: return
# only once per day
if self.__previous.date() == self.Time.date(): return
# define a small tolerance on our checks to avoid bouncing
tolerance = 0.0025
holdings = self.Portfolio[symbol].Quantity
signalDeltaPercent = (self.MACD.Current.Value - self.MACD.Signal.Current.Value)/self.MACD.Fast.Current.Value
# if our macd is greater than our signal, then let's go long
if holdings <= 0 and signalDeltaPercent > tolerance: # 0.01%
# longterm says buy as well
self.SetHoldings(symbol, 1.0)
# of our macd is less than our signal, then let's go short
elif holdings >= 0 and signalDeltaPercent < -tolerance:
self.Liquidate(symbol)
self.__previous = self.Time
def SetSignal(self):
close = self.History(symbol, 31, Resolution.Daily)['close']
todayvol = np.std(close[1:31])
yesterdayvol = np.std(close[0:30])
deltavol = (todayvol - yesterdayvol) / todayvol
self.numdays = int(round(self.numdays * (1 + deltavol)))
if self.numdays > self.ceiling:
self.numdays = self.ceiling
elif self.numdays < self.floor:
self.numdays = self.floor
self.high = self.History(symbol, self.numdays, Resolution.Daily)['high']
self.low = self.History(symbol, self.numdays, Resolution.Daily)['low']
self.buypoint = max(self.high)
self.sellpoint = min(self.low)
historyclose = self.History(symbol, self.numdays, Resolution.Daily)['close']
self.longLiqPoint = np.mean(historyclose)
self.shortLiqPoint = np.mean(historyclose)
self.yesterdayclose = historyclose.iloc[-1]
# wait for our BollingerBand to fully initialize
if not self.Bolband.IsReady: return
holdings = self.Portfolio[symbol].Quantity
if self.yesterdayclose > self.Bolband.UpperBand.Current.Value and self.Portfolio[symbol].Price >= self.buypoint:
self.SetHoldings(symbol, 1)
elif self.yesterdayclose < self.Bolband.LowerBand.Current.Value and self.Portfolio[symbol].Price <= self.sellpoint:
self.SetHoldings(symbol, -1)
if holdings > 0 and self.Portfolio[symbol].Price <= self.shortLiqPoint:
self.Liquidate(symbol)
elif holdings < 0 and self.Portfolio[symbol].Price >= self.shortLiqPoint:
self.Liquidate(symbol)
self.Log(str(self.yesterdayclose)+(" # of days ")+(str(self.numdays)))
# sort the data by daily dollar volume and take the top 'NumberOfSymbols'
def CoarseSelectionFunction(self, coarse):
# sort descending by daily dollar volume
sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)
# return the symbol objects of the top entries from our sorted collection
return [ x.Symbol for x in sortedByDollarVolume[:self.__numberOfSymbols] ]
# sort the data by P/E ratio and take the top 'NumberOfSymbolsFine'
def FineSelectionFunction(self, fine):
# sort descending by P/E ratio
sortedByPeRatio = sorted(fine, key=lambda x: x.ValuationRatios.PERatio, reverse=True)
# take the top entries from our sorted collection
return [ x.Symbol for x in sortedByPeRatio[:self.__numberOfSymbolsFine] ]