Overall Statistics
Total Trades
152
Average Win
0.06%
Average Loss
-0.05%
Compounding Annual Return
-26.960%
Drawdown
1.700%
Expectancy
-0.413
Net Profit
-1.283%
Sharpe Ratio
-5.821
Loss Rate
75%
Win Rate
25%
Profit-Loss Ratio
1.31
Alpha
-0.234
Beta
0.013
Annual Standard Deviation
0.04
Annual Variance
0.002
Information Ratio
-8.203
Tracking Error
0.051
Treynor Ratio
-18.233
Total Fees
$187.29
from QuantConnect.Data.Market import TradeBar
from datetime import timedelta
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import decimal as d

class MyAlgorithm(QCAlgorithm):
    
    def Initialize(self):
        self.SetStartDate(2017, 7, 14)  # Set Start Date
        self.SetEndDate(2017, 7, 29)
        self.SetCash(100000)  # Set Strategy Cash
        
        self.symbolData = dict()
        # I use a dictionary to create rolling windows for multiple stocks, right now it's only apple to simply things
        for ticker in ["AAPL"]:
            symbol = self.AddEquity(ticker, Resolution.Second).Symbol

            consolidator_daily = TradeBarConsolidator(timedelta(1))
            consolidator_daily.DataConsolidated += self.OnDailyData
            self.SubscriptionManager.AddConsolidator(symbol, consolidator_daily)

            consolidator_minute = TradeBarConsolidator(60)
            consolidator_minute.DataConsolidated += self.OnMinuteData
            self.SubscriptionManager.AddConsolidator(symbol, consolidator_minute)
            
            consolidator_fivemin = TradeBarConsolidator(300)
            consolidator_fivemin.DataConsolidated += self.OnDataConsolidated
            self.SubscriptionManager.AddConsolidator(symbol, consolidator_fivemin)
            
            self.symbolData[symbol] = SymbolData()

        #self.Schedule.On(self.DateRules.EveryDay(),
        #                 self.TimeRules.AfterMarketOpen('SPY', 1),
        #                 Action(self.one_minute_after_open_market))
                         
        #self.Schedule.On(self.DateRules.EveryDay(),
        #                 self.TimeRules.AfterMarketOpen('SPY', 5),
        #                 Action(self.before_close_market))
        
        self.Schedule.On(self.DateRules.EveryDay(), 
                        self.TimeRules.Every(timedelta(seconds=10)), 
                        Action(self.Tensec))
        
        self.Schedule.On(self.DateRules.EveryDay(),
                        self.TimeRules.Every(timedelta(seconds=301)),
                        Action(self.Thsec))

    # Add bars to rolling windows
    def OnDailyData(self, sender, bar):
        self.symbolData[bar.Symbol].daily_rw.Add(bar)
        
    def OnMinuteData(self, sender, bar):
        self.symbolData[bar.Symbol].minute_rw.Add(bar)
        
    def OnDataConsolidated(self,sender, bar):    
        self.symbolData[bar.Symbol].fivemin_rw.Add(bar)

    def OnData(self, data):
        for symbol in data.Keys:
            if data[symbol] is None: continue
            # Create local variable to readability
            window = self.symbolData[symbol].window
            # Update the window. If not ready, continue
            window.Add(data[symbol])
            minute = self.symbolData[symbol].minute_rw
            fivemin = self.symbolData[symbol].fivemin_rw
            if not (window.IsReady and minute.IsReady and fivemin.IsReady): continue
            if self.Portfolio[symbol].Invested:
                last_close = window[0].Close
                last_min_open = minute[1].Open
                last_min_close = minute[1].Close
                last_bar = minute[0].Close - minute[0].Open
                second_bar = minute[1].Close - minute[1].Open
                third_bar = minute[2].Close - minute[2].Open
                last_fivemin_bar = fivemin[0].Close - fivemin[0].Open
                last_fivemin_close = fivemin[1].Close
                #self.Log(str(symbol)+str(last_min_open)+", "+str(last_close))
                if (last_bar > 0 and second_bar > 0  or last_fivemin_bar > 0 or self.Portfolio[symbol].AveragePrice > last_close*d.Decimal(1.005)):
                   #self.Log(str(last_min_open)+", "+str(last_close))
                    self.Liquidate(symbol)
                    self.Log('LIQUIDATE AT THRESHOLD REACHED.')
            
                    
    def Tensec(self):
        
        for symbol in self.symbolData:
            #Create local variable to readability
            window = self.symbolData[symbol].window
            # Update the window. If not ready, continue
            minute = self.symbolData[symbol].minute_rw
            fivemin = self.symbolData[symbol].fivemin_rw
            if not (window.IsReady and minute.IsReady and fivemin.IsReady): continue    
    
            if not self.Portfolio[symbol].Invested:
                last_bar = minute[0].Close - minute[0].Open
                last_close = window[0].Close
                last_min_open = minute[1].Open
                last_min_close = minute[1].Close
                last_min_low = minute[1].Low
                last_min_high = minute[1].High
                last_fivemin_bar = fivemin[0].Close - fivemin[0].Open
                second_fivemin_bar = fivemin[1].Close - fivemin[1].Open
                #self.Log(str(last_min_open)+", "+str(last_min_close)+", "+str(last_min_low)+", "+str(last_min_high)+", "+str(last_close))
                #self.Log(str(last_bar)+", "+", "+str(second_bar)+", "+str(third_bar)+", "+str(last_close)+", "+str(minute[0].Open))
                if (last_bar < d.Decimal(-0.07) and last_fivemin_bar < 0 and second_fivemin_bar < 0):  
                    self.SetHoldings(symbol, -1.0/3.0)
                    self.Log('shorting')
                    
    def Thsec(self):
    #Creating logs to see the five-minute bars being used
        for symbol in self.symbolData:
            self.Log('argh')
            window = self.symbolData[symbol].window
            fivemin = self.symbolData[symbol].fivemin_rw   
            if not (window.IsReady and fivemin.IsReady): continue 
            self.Log(str(fivemin[0].Open)+", "+str(fivemin[0].Close)+", "+str(fivemin[0].High)+", "+str(fivemin[0].Low))
        
class SymbolData(object):
            
    def __init__(self):
        self.daily_rw = RollingWindow[TradeBar](4)
        self.minute_rw = RollingWindow[TradeBar](4)
        self.fivemin_rw = RollingWindow[TradeBar](4)
        self.window = RollingWindow[TradeBar](4)