Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
0
Tracking Error
0
Treynor Ratio
0
Total Fees
$0.00
from datetime import timedelta

class spreadFuturesExample(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2019, 1, 1)
        self.SetEndDate(2019, 1, 10)
        
        self.SetCash(100000)

        # Adds the future that will be traded and
        # set our expiry filter for this futures chain
        future = self.AddFuture(Futures.Energies.NaturalGas)
        future.SetFilter(timedelta(0), timedelta(180))
        
        # Specify futures contracts
        self.frontContract = "NG26H19"
        self.backContract = "NG27J19"

    def OnData(self, slice):
        
        # Capture the futures contracts price at 15:59 
        if not (self.Time.hour == 15 and self.Time.minute == 59): return
    
        priceFront = None
        priceBack = None
        
        if (not self.Portfolio.Invested):
            for chain in slice.FuturesChains:
                contracts = None
                # Retrieve front contract and back contract
                contracts = filter(lambda x: x.Symbol.Value in [self.frontContract,self.backContract], chain.Value)
                
                # Retrieve the price for the front and back contract 
                for contract in contracts:
                    if contract.Symbol.Value == self.frontContract:
                        priceFront = contract.LastPrice 
                    elif contract.Symbol.Value == self.backContract:
                        priceBack = contract.LastPrice 
                    
                # Calculate the spread and the ratio
                spread = priceFront - priceBack
                ratio = priceFront/priceBack
                
                # Print spread and ratio to log file
                self.Log("Spread : " + str(spread) + " - Ratio: " + str(ratio))