Overall Statistics
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Securities import *
from datetime import timedelta


class FuturesAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2013, 10, 20)
        self.SetEndDate(2013, 10, 31)
        self.SetCash(1000000)


        # Subscribe and set our expiry filter for the futures chain
        self.futureVIX = self.AddFuture(Futures.Indices.VIX)
        
        # SetFilter method accepts timedelta objects or integer for days.
        self.futureVIX.SetFilter(timedelta(5), timedelta(120))

        benchmark = self.AddEquity("SPY")
        self.SetBenchmark(benchmark.Symbol)


        self.Schedule.On(self.DateRules.EveryDay("SPY"), \
                 self.TimeRules.BeforeMarketClose("SPY", 2), \
                 self.SpecificTime)

         
    def SpecificTime(self):
        if self.Portfolio.Invested:
            assets = [asset for asset in self.Portfolio.Keys]
            to_log = { asset.ToString() : {"Holding" : self.Securities[asset].Holdings.Quantity, 
                                            "Price" : self.Portfolio[asset].Price } for asset in assets}
            
            assets = [ asset for asset in assets if to_log[asset.ToString()]["Holding"] != 0.0 ]
            to_log = { asset.ToString() : to_log[asset.ToString()] for asset in assets }
            assert len( assets ) == 1
            history = self.History( assets, 60*24*2)
            history.index = [idx[2] for idx in history.index ] 
            self.Log( "High between {} and {} is {}".format( history['high'].index[0],history['high'].index[-1], history['high'].max()))
            self.Log( "Low between {} and {} is {}".format( history['low'].index[0],history['low'].index[-1], history['low'].min()))
            self.Log( to_log )
            return

        securities = self.Securities.get_Values()
        futures = [sec for sec in securities if isinstance(sec, Securities.Future.Future)]
        
        #Find front-futures
        futures = sorted( futures, key=lambda x : x.Expiry, reverse=False)
        
        vx_futs = [fut for fut in futures if fut.Symbol.ToString().split(" ")[0] == 'VX']
        vx_fut = vx_futs[0]
        
        multiplier_vx = 1000.0
        n_units_VX = self.Portfolio.TotalPortfolioValue / (multiplier_vx * self.Portfolio[vx_fut.Symbol].Price)
        n_units_VX = int(round(n_units_VX))

        self.MarketOrder(vx_fut.Symbol, n_units_VX )