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
0
Tracking Error
0
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
from QuantConnect import *
from QuantConnect.Parameters import *
from QuantConnect.Benchmarks import *
from QuantConnect.Brokerages import *
from QuantConnect.Util import *
from QuantConnect.Interfaces import *
from QuantConnect.Algorithm import *
from QuantConnect.Algorithm.Framework import *
from QuantConnect.Algorithm.Framework.Selection import *
from QuantConnect.Algorithm.Framework.Alphas import *
from QuantConnect.Algorithm.Framework.Portfolio import *
from QuantConnect.Algorithm.Framework.Execution import *
from QuantConnect.Algorithm.Framework.Risk import *
from QuantConnect.Indicators import *
from QuantConnect.Data import *
from QuantConnect.Data.Consolidators import *
from QuantConnect.Data.Custom import *
from QuantConnect.Data.Fundamental import *
from QuantConnect.Data.Market import *
from QuantConnect.Data.UniverseSelection import *
from QuantConnect.Notifications import *
from QuantConnect.Orders import *
from QuantConnect.Orders.Fees import *
from QuantConnect.Orders.Fills import *
from QuantConnect.Orders.Slippage import *
from QuantConnect.Scheduling import *
from QuantConnect.Securities import *
from QuantConnect.Securities.Equity import *
from QuantConnect.Securities.Forex import *
from QuantConnect.Securities.Interfaces import *
from datetime import date, datetime, timedelta
from QuantConnect.Python import *
from QuantConnect.Storage import *
QCAlgorithmFramework = QCAlgorithm
QCAlgorithmFrameworkBridge = QCAlgorithm
import math
import numpy as np
import pandas as pd
import scipy as sp
import string


class FiveDayUp(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2021, 5 , 19)  # Set Start Date
        self.SetCash(100000)  # Set Strategy Cash
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash)
        self.UniverseSettings.Resolution = Resolution.Hour
        self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
        self.uptrend = []
        self.rebalance_interval = timedelta(days = 1)
        self.lasttime = None
        self.curr_universe = []
        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.Every(timedelta(seconds=1)), self.UpdateCurrLong)
        self.length_up = 3
        self.dict = {}
        
    def UpdateCurrLong(self):
        interval = 3600*(self.Time.hour-17) + 60*(self.Time.minute - 5) + self.Time.second
        if interval < 0:
            self.uptrend = []
        if interval >= 0 and interval < 26*27:
            #self.Debug(f'INTERVAL #: {interval}')
            #for sym in self.curr_universe:
            for sym in self.dict.keys():
                cont = False
                if sym.Value[0] == string.ascii_uppercase[math.floor(interval/27)]:
                    if interval % 27 == 26:
                        if len(sym.Value) == 1:
                            cont = True
                    elif len(sym.Value) > 1:
                        if sym.Value[1] == string.ascii_uppercase[interval % 27]:
                            cont = True
                if cont == True:
                    hist_obj = hist_window(self,sym)
                    if hist_obj.is_week_up() == False:
                        continue
                    if hist_obj.is_day_up() == False:
                        continue
                    #self.Log(f'INTERVAL: {interval}, current UPTREND: {self.uptrend}')
                    self.uptrend.append(sym.Value)
        if interval == 26*27-1:
            self.Log(f'UPTREND: {self.uptrend}')
            interval = None
        
    def CoarseSelectionFunction(self,coarse):
        return [x.Symbol for x in coarse]
    
    def FineSelectionFunction(self,fine):
        #self.curr_universe = [f.Symbol for f in fine]
        self.curr_universe = [f.Symbol for f in fine if f.Symbol.Value == "EZPW"]
        for sym in self.curr_universe:
            self.dict[sym]=hist_window(self,sym)
        return self.curr_universe




class hist_window():
    def __init__(self,algorithm,symbol):
        self.algorithm = algorithm
        self.length_up = algorithm.length_up
        self.Symbol = symbol
        
        self.WeekWindow = RollingWindow[TradeBar](self.length_up)
        self.WeekConsolidator = TradeBarConsolidator(timedelta(weeks=1))
        self.WeekConsolidator.DataConsolidated += self.OnWeekConsolidated
        
    def is_day_up(self):
        #self.hourbars = [TradeBar(bar.Index[1], self.Symbol, bar.open, bar.high, bar.low, bar.close, bar.volume) for bar in self.algorithm.History(self.Symbol, timedelta(days = 3) , Resolution.Hour).itertuples()]
        self.hourbars = [bar for bar in self.algorithm.History(self.Symbol, self.length_up*8 , Resolution.Hour).itertuples()]
        self.algorithm.Debug(f'{[(str(bar.Index[1]),bar.high,bar.low,bar.close) for bar in self.hourbars]}')
        consol_day = []
        day = None
        high = None
        low = None
        close = None
        for i in range(len(self.hourbars)):
            bar = self.hourbars[i]
            if day == None:
                high = bar.high
                low = bar.low
                close = bar.close
                day = bar.Index[1].day
            elif bar.Index[1].day != day:
                consol_day.append((high,low,close))
                #consol_day.append((high,low))
                high = bar.high
                low = bar.low
                close = bar.close
                day = bar.Index[1].day
            else:
                high = max(high,bar.high)
                low = min(low,bar.low)
                close = bar.close
            
            if i == len(self.hourbars)-1:
                consol_day.append((high,low,close))
                #consol_day.append((high,low))
        #self.algorithm.Debug(f'CONSOL_DAY: {consol_day}')
        for i in range(1,len(consol_day)):
            for j in range(len(consol_day[-i])):
                if consol_day[-i][j]<= consol_day[-i-1][j]:
                    return False
        return True
    
    def is_week_up(self):
        self.bars = [TradeBar(bar.Index[1], self.Symbol, bar.open, bar.high, bar.low, bar.close, bar.volume) for bar in self.algorithm.History(self.Symbol, self.length_up*7 , Resolution.Daily).itertuples()]
        if len(self.bars)<self.length_up*7:
            return False
        for bar in self.bars:
            #daily_tradebar = TradeBar(bar.Index[1], self.Symbol, bar.open, bar.high, bar.low, bar.close, bar.volume)
            self.WeekConsolidator.Update(bar)
        for i in range(self.length_up-1):
            if self.WeekWindow[i].High<=self.WeekWindow[i+1].High:
                return False
            if self.WeekWindow[i].Low<=self.WeekWindow[i+1].Low:
                return False
            if self.WeekWindow[i].Close<=self.WeekWindow[i+1].Close:
                return False
        return True
    
    def OnWeekConsolidated(self, sender, bar):
        #self.algorithm.Debug('WeekWindow')
        self.WeekWindow.Add(bar)