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
5.35
Tracking Error
0.107
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
#region imports
from AlgorithmImports import *
#endregion
import datetime
import pandas as pd
import ht_auth

class ModulatedHorizontalAutosequencers(QCAlgorithm):

    def Initialize(self):
        
        ht_auth.SetToken(self.GetParameter("mlfinlab-api-key"))
        import mlfinlab as ml
        self.ml = ml

        self.SetStartDate(2019, 1, 18)  # Set Start Date
        self.SetEndDate(2019, 1, 22)
        self.SetCash(100000)  # Set Strategy Cash

        self.spy = self.AddEquity("SPY", Resolution.Tick).Symbol
        self.windowsize = 10000
        self.batch_size=1000000
        self.lastsample = datetime.datetime.min
        self.initialisation = True
        self.runningtotal = 0
        self.dollarhistory = pd.DataFrame()
        self.threshold = 500000000

        self.SetWarmUp(10000)

    def OnData(self, data):

        if data:
            dollarvolumes = [tick.LastPrice * tick.Quantity for tick in data[self.spy]]
            self.runningtotal += sum(dollarvolumes)

            if self.runningtotal > self.threshold and data.Time > self.lastsample:
                
                if self.lastsample == datetime.datetime.min:
                    self.lastsample = data.Time
                    self.threshold = self.GetAvgDollarVolume(self.spy, data.Time, 5) / 50
                
                history = self.History(self.spy, 
                    self.lastsample, 
                    data.Time, 
                    Resolution.Tick)

                history = history[["lastprice", "quantity"]]
                history = history.loc[self.spy]
            
                nextdollarbar = self.Ticks_to_Dollars(history, self.threshold, self.batch_size)

                self.dollarhistory = pd.concat([self.dollarhistory, nextdollarbar]).drop_duplicates().reset_index(drop=True).iloc[-self.windowsize:]

                self.runningtotal =0
                self.lastsample = data.Time

                self.threshold = self.GetAvgDollarVolume(self.spy, data.Time, 5) / 50
                                
                self.Debug(str(data.Time)+" New Dollar Bar. total bars in history: "+str(len(self.dollarhistory))+" new threshold: "+str(self.threshold))

    def Ticks_to_Dollars(self, ticks, threshold, batch_size):
        
        df = pd.DataFrame()
        df["date_time"] = ticks.index.values
        df["price"] = ticks.lastprice.values
        df["volume"] = ticks.quantity.values
    
        return self.ml.data_structures.get_dollar_bars(df,
                                        threshold = threshold,
                                        batch_size = batch_size,
                                        verbose = False)

    def GetAvgDollarVolume(self, security, time, lookback):
        
        volhistory = self.History(security, time - timedelta(days = lookback), time, Resolution.Daily)
        dollarvolumes = [day[1].close * day[1].volume for day in volhistory.iterrows()]
        
        return sum(dollarvolumes)/len(dollarvolumes)