Overall Statistics
# region imports
from AlgorithmImports import *
import pandas as pd
import numpy as np
from datetime import time, datetime, timedelta
# endregion

class CombinedAlgorithm(QCAlgorithm):
	
    def Initialize(self):

        # INITIALIZE
        self.SetStartDate(2022, 1, 1)  # Set Start Date
        self.SetEndDate(2022, 2, 1)
        self.SetCash(10000)  # Set Strategy Cash
        self.spy = self.AddEquity('SPY', Resolution.Minute)
        self.spy.SetDataNormalizationMode(DataNormalizationMode.Raw)

        # SCHEDULED EVENTS
        self.Schedule.On(self.DateRules.WeekStart("SPY"), self.TimeRules.AfterMarketOpen("SPY"), self.WeekStart)
        self.Schedule.On(self.DateRules.WeekEnd("SPY"), self.TimeRules.BeforeMarketClose("SPY"), self.WeekEnd)
        self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.AfterMarketOpen("SPY"), self.DailyCheck)


        # TOGGLES
        # self.short_ema_trail = True
        self.invest = False
        self.weekly_trigger = False
        self.buy = False

        # VARIABLES
        self.trigger_week_high = 0
        self.trigger_week_low = 0

        self.SetWarmUp(timedelta(days = 20))

        weeklyConsolidator = TradeBarConsolidator(timedelta(weeks=1))
        self.SubscriptionManager.AddConsolidator(self.spy.Symbol, weeklyConsolidator)
        weeklyConsolidator.DataConsolidated += self.OnTwoWeekBar
        self.weekBarWindow = RollingWindow[TradeBar](1) # 2

        # CUSTOM CHART
        log_plot = Chart('Custom Chart')
        log_plot.AddSeries(Series('Orders',SeriesType.Scatter,0))
        log_plot.AddSeries(Series('Spy Price', SeriesType.Line,0))
        self.AddChart(log_plot) 

    def Rebalance(self):
        if self.IsWarmingUp:
            return

    def OnData(self, data):
        # VARIABLES
        spy_price = self.Securities[self.spy.Symbol].Price
        held_stocks = self.Portfolio[self.spy.Symbol].Quantity
        shares_to_buy = int(self.Portfolio.Cash / spy_price)
        profit = self.Portfolio[self.spy.Symbol].UnrealizedProfitPercent

        if (spy_price > self.trigger_week_high) and self.weekly_trigger and self.invest:
            self.MarketOrder(self.spy.Symbol, (shares_to_buy*0.1))
            self.invest = False
            self.weekly_trigger = False
            self.Log(f'{self.trigger_week_high} previous weeks high ORDER')

    def OnTwoWeekBar(self, sender, bar):
        self.weekBarWindow.Add(bar)

        if not self.weekBarWindow.IsReady:
            return         
        
        trigger_week = self.weekBarWindow[0]
       
        self.trigger_week_high = trigger_week.High
        self.trigger_week_low = trigger_week.Low
        self.Log(f'{self.trigger_week_high} previous weeks high')

    def WeekStart(self):
            self.weekly_trigger = True
            self.invest = True

    def WeekEnd(self):
        if self.weekly_trigger or self.invest:
            self.weekly_trigger = False
            self.invest = False

    def DailyCheck(self):
        self.Log(f'{self.trigger_week_high} Daily one')

    def OnOrderEvent(self, orderEvent):
        if orderEvent.FillQuantity == 0:
            return

        fetched = self.Transactions.GetOrderById(orderEvent.OrderId)
        symbol = orderEvent.Symbol
        fill_price = orderEvent.FillPrice
            
        self.Plot('Custom Chart', 'Orders', fill_price)