Overall Statistics
Total Trades
10
Average Win
0.02%
Average Loss
0%
Compounding Annual Return
6.521%
Drawdown
0.000%
Expectancy
0
Net Profit
0.104%
Sharpe Ratio
54.311
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
100%
Profit-Loss Ratio
0
Alpha
0.056
Beta
-0.002
Annual Standard Deviation
0.001
Annual Variance
0
Information Ratio
-11.032
Tracking Error
0.083
Treynor Ratio
-23.37
Total Fees
$96.63
Estimated Strategy Capacity
$3700000.00
Lowest Capacity Asset
KAVL XQJXBPPDMGYT
from Risk.MaximumDrawdownPercentPerSecurity import MaximumDrawdownPercentPerSecurity
class TransdimensionalParticleThrustAssembly(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2021, 10, 24)                                                     # Set Start Date
        self.SetEndDate(2021, 10, 30)                                                       # Set End Date
        self.SetCash(1000000)                                                               # Set Strategy Cash
        self.AddEquity("SPY", Resolution.Minute)                                            #.SetDataNormalizationMode(DataNormalizationMode.SplitAdjusted) # Trade any day SPY is trading
        self.UniverseSettings.Resolution = Resolution.Minute                                # Setting Universe: Daily, Minute or Second
        self.SetSecurityInitializer(self.CustomSecurityInitializer)
        self.UniverseSettings.FillForward = False
        self.UniverseSettings.ExtendedMarketHours = True
        self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
        self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.At(9, 30), self.Rebalance)
        self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.At(9, 33), self.Rebalance_Second)
        self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.BeforeMarketClose("SPY", 29), self.Parameters_Two)
        self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.BeforeMarketClose("SPY", 30), self.LiquidatePositions)
        self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.BeforeMarketClose("SPY", 1), self.OnMarketClose)
        self.previous_d_close = {}                                                          # Dictionary to keep track of previous close for each symbol
        self.filtered = []
        self.donottrade = [Symbol.Create(ticker, SecurityType.Equity, Market.USA) for ticker in ['HUGE', 'PRTO', 'NLNK', 'IMAC', 'ENT', 'AXAS', 'MDLY', 'CHFS', 'NTEC', 'PSHG',
                        'DSE', 'FET', 'MGEN', 'WYY', 'JILL', 'RMED', 'CVEO', 'HTGM', 'HJLI', 'CDR', 'UAN', 'TRVI', 'PRT', 'CSPI', 'RCEL', 'FTSI']] #, 'MSFT']]
        self.cashused = 1000

    def OnData(self, data):                                                                 
        pass
    
    def CoarseSelectionFunction(self, coarse):                                              # Picks up securities Universe.  Constructed at midnight of night before.
        return [x.Symbol for x in coarse if 10000 > x.Price]
    
    def FineSelectionFunction(self, fine):                                                  # Picks up securities from Coarse > Universe.  Constructed at midnight of night before.
        return [x.Symbol for x in fine if x.MarketCap < 5000000000]

    def OnSecuritiesChanged(self, changes):                                                 # Picks up securities from the Fine > Coarse > Universe.  Constructed at midnight of night before.
        for security in changes.AddedSecurities:                                            # AddedSecurities are those populated by Fine > Coarse > Universe, for security in self.ActiveSecurities.Values
            if security.Symbol in self.donottrade:
                continue
            symbol = security.Symbol
            if symbol not in self.previous_d_close:                                         # Make a history call for symbol to get last closing price
                history = self.History(symbol, 1, Resolution.Daily)                         #, DataNormalizationMode.SplitAdjusted)
                if not history.empty:
                    history = history.close.unstack(0)[symbol]
                    if not history.empty:
                        self.previous_d_close[symbol] = history[0]
        for security in changes.RemovedSecurities:                                          # Remove symbols from previous close as they are removed from the universe
            self.previous_d_close.pop(security.Symbol, None)

    def Rebalance(self):
        percent_change = {}                                                                 # Dictionary to keep track of percent change from last close
        price_restriction = {}
        before_filtered = []
        vol_minimum = {}
        for symbol, previous_d_close in self.previous_d_close.items():                      # Populate Dictionary
            if self.CurrentSlice.ContainsKey(symbol):
                if self.CurrentSlice[symbol]:
                    last_price = self.CurrentSlice[symbol].Close
                    percent_change[symbol] = last_price / previous_d_close
                    price_restriction[symbol] = last_price
            symbols = list(percent_change.keys())                                           # Symbols under consideration
            sorted_symbols = sorted([x for x in symbols if percent_change[x] > 1.2 and price_restriction[x] > 1], key=lambda x : percent_change[x], reverse = True) # True is Highest first
            before_filtered = sorted_symbols#[:1]                                           # Get top xx symbols
        for symbol in before_filtered:
            if self.CurrentSlice.ContainsKey(symbol):
                history_min_v = self.History(symbol, 60, Resolution.Minute).volume.unstack(level=0)[symbol]
                current_price = self.CurrentSlice[symbol].Close
                vol_sum = history_min_v[-60:].sum()
                vol_minimum[symbol] = vol_sum * current_price
                symbols = list(vol_minimum.keys())
                self.filtered = sorted([x for x in symbols if vol_minimum[x] > 2000000], key=lambda x: vol_minimum[x], reverse = True)[:1]

    def Rebalance_Second(self):
        for symbol in self.filtered:
            price = self.Securities[symbol].Price #self.Portfolio[symbol].AveragePrice
            self.LimitOrder(symbol, -self.cashused/price, round((price * 0.99), 2))         #self.MarketOrder(symbol, -self.cashused/price) #self.StopMarketOrder(symbol, -self.cashused/price, price*1.2)

    def Parameters_Two(self):
        for symbol in self.filtered:
            if self.CurrentSlice.Bars.ContainsKey(symbol):
                history_min_v = self.History(symbol, 361, Resolution.Minute).volume.unstack(level=0)[symbol]
                if not history_min_v.empty:
                    fifteen_min_v = round(history_min_v[-361:-347].sum(), 0)
                    fifteen_to_thirty_v =round(history_min_v[-346:-332].sum(), 0)
                    thirty_min_v = round(history_min_v[-361:-332].sum(), 0)
                    one_h_v = round(history_min_v[-331:-302].sum(), 0)
                    one_h_half_v = round(history_min_v[-301:-272].sum(), 0)
                    two_h_v = round(history_min_v[-271:-242].sum(), 0)
                    three_h_v = round(history_min_v[-241:-182].sum(), 0)
                    four_h_v = round(history_min_v[-181:-122].sum(), 0)
                    five_h_v = round(history_min_v[-121:-62].sum(), 0)
                    six_h_v = round(history_min_v[-61:-1].sum(), 0)
                    symbol = symbol.Value
                    self.Log("; {0} ; {1} ; {2} ; {3} ; {4} ; {5} ; {6} ; {7} ; {8} ; {9} ; {10} ".format(
                        symbol, fifteen_min_v, fifteen_to_thirty_v, thirty_min_v, one_h_v, one_h_half_v, two_h_v, three_h_v, four_h_v, five_h_v, six_h_v))

    def LiquidatePositions(self):
        self.Liquidate()                                                                    # Liquidate portfolio
    def CustomSecurityInitializer(self, security):
        security.SetDataNormalizationMode(DataNormalizationMode.SplitAdjusted)
        security.SetFeeModel(CustomFeeModel())
    def OnMarketClose(self):
        for symbol in self.previous_d_close:                                                # Store new previous close values
            if self.CurrentSlice.ContainsKey(symbol):
                self.previous_d_close[symbol] = self.CurrentSlice[symbol].Close

class CustomFeeModel():
    def GetOrderFee(self, parameters):
        loss_total = (parameters.Security.Price * 0.01 * parameters.Order.AbsoluteQuantity) + (parameters.Order.AbsoluteQuantity * 0.005)
        fee = max(1, loss_total)
        return OrderFee(CashAmount(fee, 'USD'))