Overall Statistics
Total Trades
1589
Average Win
0.00%
Average Loss
0.00%
Compounding Annual Return
0.181%
Drawdown
0.100%
Expectancy
0.944
Net Profit
0.365%
Sharpe Ratio
1.166
Probabilistic Sharpe Ratio
61.226%
Loss Rate
31%
Win Rate
69%
Profit-Loss Ratio
1.83
Alpha
0.001
Beta
-0.003
Annual Standard Deviation
0.001
Annual Variance
0
Information Ratio
-0.357
Tracking Error
0.152
Treynor Ratio
-0.452
Total Fees
$3416.35
Estimated Strategy Capacity
$450000000000.00
Lowest Capacity Asset
ES XKGCMV4QK9VL
#region imports
from datetime import datetime, timedelta
import datetime
from AlgorithmImports import *
import pandas as pd
from io import StringIO
from QuantConnect.Python import *
from QuantConnect.Indicators import RollingWindow
#

#endregion
class RetrospectiveTanButterfly(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2020, 9, 17)  
        #self.SetEndDate(2022, 9, 24)
        self.SetEndDate(2022, 9, 23)
        self.SetCash(1000000000) 
        self.symbolData = {}

        self.contract = self.AddFuture(Futures.Indices.SP500EMini , Resolution.Second, extendedMarketHours = False, dataNormalizationMode = DataNormalizationMode.BackwardsRatio, dataMappingMode = DataMappingMode.OpenInterest , contractDepthOffset = 0)
        symbol = self.contract.Symbol
        self.test1 = True
        self.list = [[self.Time,1]]
        self.trades_df = pd.DataFrame(self.list,columns=['entry','direction'])

        self.symbolData[symbol] = SymbolData()
        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(6, 30), self.start)
        #self.symbolData[symbol].bidPrice = self.Securities[symbol].BidPrice
    
    def start(self):
        symbol = self.contract.Symbol

        for symbol, symbolData in self.symbolData.items():
            if self.test1 == True:    
                self.test1 = False    
                data = self.Download("https://docs.google.com/spreadsheets/d/1NIbICr3S13U1zavi5AxOO9s_4GAg1RRXICn48j17498/export?format=csv")
                rows = [] 
                for row in data.split('\n'):
                        rows.append(row.split(','))
                self.trades_df = pd.DataFrame(np.array(rows[1:]),columns=['entry','direction'])
                self.trades_df['direction'] = self.trades_df['direction'].str.strip('\r')
                #self.trades_df = self.trades_df.head(100)
                self.trades_df['entry'] = pd.to_datetime(self.trades_df['entry'], yearfirst=True)
                symbolData.trades_df = self.trades_df
                self.Log(f'df len symboldata after init {len(symbolData.trades_df)}')

        symbolData = self.symbolData[symbol]
        today = self.Time
        oneday = self.Time+timedelta(days=1)
        self.trades_df = symbolData.trades_df
        #convert pandas to timedelta/datetime
        self.trades_df = self.trades_df.loc[(self.trades_df['entry']>=today) & (self.trades_df['entry']<oneday)]
        self.Log(f'df len for next day {len(self.trades_df)}')


    def OnData(self, data): 
        


        #loop through entries in google sheet to place them when self.Time matches
        if len(self.trades_df)>0:
            for trade in self.trades_df.itertuples():
                if self.Time == trade.entry:
                    self.MarketOrder(self.contract.Mapped, trade.direction)
        

class SymbolData:
    
    def __init__(self):
        self.trades_df = 0