Overall Statistics
Total Trades
7
Average Win
0%
Average Loss
0%
Compounding Annual Return
4.723%
Drawdown
1.400%
Expectancy
0
Net Profit
0.952%
Sharpe Ratio
0.948
Probabilistic Sharpe Ratio
48.553%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
-0.022
Beta
0.244
Annual Standard Deviation
0.035
Annual Variance
0.001
Information Ratio
-1.886
Tracking Error
0.102
Treynor Ratio
0.137
Total Fees
$7.00
Estimated Strategy Capacity
$2700000000.00
Lowest Capacity Asset
SPY R735QTJ8XC9X
# region imports
from AlgorithmImports import *
import pandas as pd
import numpy as np
from datetime import time, datetime, timedelta
# endregion

class RollingWindowAlgorithm(QCAlgorithm):

    def Initialize(self):

        self.SetStartDate(2021,1,1) 
        self.SetEndDate(2021,3, 16)
        self.SetCash(10000)
        self.spy = self.AddEquity("SPY", Resolution.Daily)
        self.spy.SetDataNormalizationMode(DataNormalizationMode.Raw)

        # TOGGLES
        self.invest = True
        self.sell = True
        self.liquidate = True

        log_plot = Chart('Custom Chart')
        log_plot.AddSeries(Series('Orders',SeriesType.Scatter,0))
        log_plot.AddSeries(Series('Close Price', SeriesType.Line,0))
        
        self.AddChart(log_plot)

        # Creates a Rolling Window 
        self.trade_bars = RollingWindow[TradeBar](3)

    def OnData(self, data):
        self.Plot('Custom Chart', 'Close Price', self.Securities[self.spy.Symbol].Close)
        profit = self.Portfolio[self.spy.Symbol].UnrealizedProfitPercent
        spy_price = self.Securities[self.spy.Symbol].Price

        # Add SPY TradeBar in rollling window
        self.trade_bars.Add(data["SPY"])

        # Wait for trade_bars to be ready.
        if not (self.trade_bars.IsReady): return

        third_bar = self.trade_bars[0] # Current Day
        second_bar = self.trade_bars[1]
        first_bar = self.trade_bars[2]

        # 1-2u
        if (second_bar.High < first_bar.High) and (second_bar.Low > first_bar.Low):
            if (third_bar.Price > second_bar.High):
                    shares_to_buy = int(self.Portfolio.Cash / data[self.spy.Symbol].Open)
                    self.MarketOrder(self.spy.Symbol, (shares_to_buy*0.1))

        # 2d-2u
        if (second_bar.High < first_bar.High) and (second_bar.Low < first_bar.Low):
            if (third_bar.Price > second_bar.High):
                    shares_to_buy = int(self.Portfolio.Cash / data[self.spy.Symbol].Open)
                    self.MarketOrder(self.spy.Symbol, (shares_to_buy*0.1))

        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)
            self.Log(f"{str(fetched.Type)} was filled. Symbol: {str(orderEvent.Symbol)}. \
                Quantity: {str(orderEvent.FillQuantity)}. Direction: {str(orderEvent.Direction)}")