Overall Statistics
from datetime import datetime
import decimal
import numpy as np

class DynamicBreakoutAlgorithm(QCAlgorithm):
    
    def Initialize(self):
        self.SetStartDate(2018,1,1)
        self.SetEndDate(datetime.now())
        self.SetCash(100000)
        Equity = self.AddEquity("AAPL", Resolution.Daily)
        Equity = self.AddEquity("NVDA", Resolution.Daily)
        self.syl = Equity.Symbol
        self.Schedule.On(self.DateRules.EveryDay(self.syl), self.TimeRules.BeforeMarketClose(self.syl,1),Action(self.SetSignal))
        self.numdays = 20
        self.ceiling,self.floor = 60,20
        self.buypoint, self.sellpoint= None, None
        self.longLiqPoint, self.shortLiqPoint, self.yesterdayclose= None, None, None
        self.SetBenchmark(self.syl)
        self.Bolband = self.BB(self.syl, self.numdays, 2, MovingAverageType.Simple, Resolution.Daily)
        self.__macd = self.MACD("AAPL", 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily)
        self.__macd = self.MACD("NVDA", 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily)
        self.__previous = datetime.min
        self.PlotIndicator("MACD", True, self.__macd, self.__macd.Signal)
        self.PlotIndicator("AAPL", self.__macd.Fast, self.__macd.Slow)
        self.PlotIndicator("NVDA", self.__macd.Fast, self.__macd.Slow)
        self.aapl = self.AddEquity("AAPL", Resolution.Daily).Symbol
        self.nvda = self.AddEquity("NVDA", Resolution.Daily).Symbol
        self.cache = {    
            self.aapl: SymbolData(self.aapl, self),
            self.nvda: SymbolData(self.nvda, self)
}
   
    def SetSignal(self):
        
        close = self.History(self.syl, 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(self.syl, self.numdays, Resolution.Daily)['high']
        self.low = self.History(self.syl, self.numdays, Resolution.Daily)['low']      

        self.buypoint = max(self.high)
        self.sellpoint = min(self.low)
        historyclose = self.History(self.syl, 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[self.syl].Quantity
    
        if self.yesterdayclose > self.Bolband.UpperBand.Current.Value and self.Portfolio[self.syl].Price >= self.buypoint:
            self.SetHoldings(self.syl, 1)
        elif self.yesterdayclose < self.Bolband.LowerBand.Current.Value and self.Portfolio[self.syl].Price <= self.sellpoint:
            self.SetHoldings(self.syl, -1)

        if holdings > 0 and self.Portfolio[self.syl].Price <= self.shortLiqPoint:
            self.Liquidate(self.syl)
        elif holdings < 0 and self.Portfolio[self.syl].Price >= self.shortLiqPoint:
            self.Liquidate(self.syl)
      
        self.Log(str(self.yesterdayclose)+(" # of days ")+(str(self.numdays)))
        
    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.cache[self.syl].MACD: 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["AAPL"].Quantity
        holdings = self.Portfolio["NVDA"].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("AAPL", 1.0)
            self.SetHoldings("NVDA", 1.0)

        # of our macd is less than our signal, then let's go short
        elif holdings >= 0 and signalDeltaPercent < -tolerance:
            self.Liquidate("AAPL")
            self.Liquidate("NVDA")


        self.__previous = self.Time
from datetime import datetime
import decimal
import numpy as np
from Alphas.MacdAlphaModel import MacdAlphaModel

class SymbolData:
    def __init__(self, symbol, algorithm):
        self.Symbol = symbol
        self.MACD = algorithm.MACD(symbol, 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily)
        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.aapl = self.AddEquity("AAPL", Resolution.Daily).Symbol
        self.nvda = self.AddEquity("NVDA", Resolution.Daily).Symbol
        self.cache = {    
            self.aapl: SymbolData(self.aapl, self),
            self.nvda: SymbolData(self.nvda, self)
}

    def SetSignal(self):
        
        close = self.History(self.syl, 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(self.syl, self.numdays, Resolution.Daily)['high']
        self.low = self.History(self.syl, self.numdays, Resolution.Daily)['low']      

        self.buypoint = max(self.high)
        self.sellpoint = min(self.low)
        historyclose = self.History(self.syl, 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[self.syl].Quantity
    
        if self.yesterdayclose > self.Bolband.UpperBand.Current.Value and self.Portfolio[self.syl].Price >= self.buypoint:
            self.SetHoldings(self.syl, 1)
        elif self.yesterdayclose < self.Bolband.LowerBand.Current.Value and self.Portfolio[self.syl].Price <= self.sellpoint:
            self.SetHoldings(self.syl, -1)

        if holdings > 0 and self.Portfolio[self.syl].Price <= self.shortLiqPoint:
            self.Liquidate(self.syl)
        elif holdings < 0 and self.Portfolio[self.syl].Price >= self.shortLiqPoint:
            self.Liquidate(self.syl)
      
        self.Log(str(self.yesterdayclose)+(" # of days ")+(str(self.numdays)))
        
    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[self.cache].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("AAPL", 1.0)
            self.SetHoldings("NVDA", 1.0)

        # of our macd is less than our signal, then let's go short
        elif holdings >= 0 and signalDeltaPercent < -tolerance:
            self.Liquidate("AAPL")
            self.Liquidate("NVDA")


        self.__previous = self.Time
from datetime import datetime
import decimal
import numpy as np

class DynamicBreakoutAlgorithm(QCAlgorithm):
    
    def Initialize(self):
        self.SetStartDate(2018,1,1)
        self.SetEndDate(datetime.now())
        self.SetCash(100000)
        Equity = self.AddEquity("NVDA", Resolution.Daily)
        self.syl = Equity.Symbol
        self.Schedule.On(self.DateRules.EveryDay(self.syl), self.TimeRules.BeforeMarketClose(self.syl,1),Action(self.SetSignal))
        self.numdays = 20
        self.ceiling,self.floor = 60,20
        self.buypoint, self.sellpoint= None, None
        self.longLiqPoint, self.shortLiqPoint, self.yesterdayclose= None, None, None
        self.SetBenchmark(self.syl)
        self.Bolband = self.BB(self.syl, self.numdays, 2, MovingAverageType.Simple, Resolution.Daily)
        self.__macd = self.MACD("NVDA", 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily)
        self.__previous = datetime.min
        self.PlotIndicator("MACD", True, self.__macd, self.__macd.Signal)
        self.PlotIndicator("NVDA", self.__macd.Fast, self.__macd.Slow)
   
    def SetSignal(self):
        
        close = self.History(self.syl, 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(self.syl, self.numdays, Resolution.Daily)['high']
        self.low = self.History(self.syl, self.numdays, Resolution.Daily)['low']      

        self.buypoint = max(self.high)
        self.sellpoint = min(self.low)
        historyclose = self.History(self.syl, 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[self.syl].Quantity
    
        if self.yesterdayclose > self.Bolband.UpperBand.Current.Value and self.Portfolio[self.syl].Price >= self.buypoint:
            self.SetHoldings(self.syl, 1)
        elif self.yesterdayclose < self.Bolband.LowerBand.Current.Value and self.Portfolio[self.syl].Price <= self.sellpoint:
            self.SetHoldings(self.syl, -1)

        if holdings > 0 and self.Portfolio[self.syl].Price <= self.shortLiqPoint:
            self.Liquidate(self.syl)
        elif holdings < 0 and self.Portfolio[self.syl].Price >= self.shortLiqPoint:
            self.Liquidate(self.syl)
      
        self.Log(str(self.yesterdayclose)+(" # of days ")+(str(self.numdays)))
        
    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["NVDA"].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("NVDA", 1.0)

        # of our macd is less than our signal, then let's go short
        elif holdings >= 0 and signalDeltaPercent < -tolerance:
            self.Liquidate("NVDA")


        self.__previous = self.Time
from datetime import datetime
import decimal
import numpy as np

class DynamicBreakoutAlgorithm(QCAlgorithm):
    
    def Initialize(self):
        self.SetStartDate(2018,1,1)
        self.SetEndDate(datetime.now())
        self.SetCash(100000)
        Equity = self.AddEquity("AAPL", Resolution.Daily)
        self.syl = Equity.Symbol
        self.Schedule.On(self.DateRules.EveryDay(self.syl), self.TimeRules.BeforeMarketClose(self.syl,1),Action(self.SetSignal))
        self.numdays = 20
        self.ceiling,self.floor = 60,20
        self.buypoint, self.sellpoint= None, None
        self.longLiqPoint, self.shortLiqPoint, self.yesterdayclose= None, None, None
        self.SetBenchmark(self.syl)
        self.Bolband = self.BB(self.syl, self.numdays, 2, MovingAverageType.Simple, Resolution.Daily)
        self.__macd = self.MACD("AAPL", 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily)
        self.__previous = datetime.min
        self.PlotIndicator("MACD", True, self.__macd, self.__macd.Signal)
        self.PlotIndicator("AAPL", self.__macd.Fast, self.__macd.Slow)
   
    def SetSignal(self):
        
        close = self.History(self.syl, 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(self.syl, self.numdays, Resolution.Daily)['high']
        self.low = self.History(self.syl, self.numdays, Resolution.Daily)['low']      

        self.buypoint = max(self.high)
        self.sellpoint = min(self.low)
        historyclose = self.History(self.syl, 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[self.syl].Quantity
    
        if self.yesterdayclose > self.Bolband.UpperBand.Current.Value and self.Portfolio[self.syl].Price >= self.buypoint:
            self.SetHoldings(self.syl, 1)
        elif self.yesterdayclose < self.Bolband.LowerBand.Current.Value and self.Portfolio[self.syl].Price <= self.sellpoint:
            self.SetHoldings(self.syl, -1)

        if holdings > 0 and self.Portfolio[self.syl].Price <= self.shortLiqPoint:
            self.Liquidate(self.syl)
        elif holdings < 0 and self.Portfolio[self.syl].Price >= self.shortLiqPoint:
            self.Liquidate(self.syl)
      
        self.Log(str(self.yesterdayclose)+(" # of days ")+(str(self.numdays)))
        
    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["AAPL"].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("AAPL", 1.0)

        # of our macd is less than our signal, then let's go short
        elif holdings >= 0 and signalDeltaPercent < -tolerance:
            self.Liquidate("AAPL")


        self.__previous = self.Time