Overall Statistics
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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
import numpy as np

class CurveSteepener(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2009, 1, 1)
        self.SetEndDate(2011, 1, 1)
        self.SetCash(100000)

        y2future = self.AddFuture(Futures.Financials.Y2TreasuryNote)
        y2future.SetFilter(timedelta(0), timedelta(182))
        y10future = self.AddFuture(Futures.Financials.Y10TreasuryNote)
        y10future.SetFilter(timedelta(0), timedelta(182))
        self.y2contract = None
        self.y10contract = None

        equity = self.AddEquity("SPY", Resolution.Daily)
        self.Schedule.On(self.DateRules.MonthStart("SPY"), self.TimeRules.AfterMarketOpen("SPY"), self.RebalancingCode)

    def RebalancingCode(self):
        if self.y2contract and self.y10contract:
            self.Liquidate()
            self.MarketOrder(self.y10contract.Symbol, -10)
            self.MarketOrder(self.y2contract.Symbol, 20)

    def OnData(self, slice):
        # Keep track of which futures contracts we want
        for chain in slice.FuturesChains:
            # find the front contract expiring no earlier than in 90 days
            contracts = list(filter(lambda x: x.Expiry > self.Time + timedelta(30), chain.Value))
            # if there is any contract, trade the front contract
            if len(contracts) == 0: continue
            contract = sorted(contracts, key = lambda x: x.Expiry, reverse=True)[0]
    
            if str(contract.Symbol.ID).startswith('ZT'):
                self.y2contract = contract
            if str(contract.Symbol.ID).startswith('ZN'):
                self.y10contract = contract