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
Probabilistic 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
# 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.Algorithm.Framework")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Orders import *
from QuantConnect.Algorithm import *
from QuantConnect.Algorithm.Framework import *
from QuantConnect.Algorithm.Framework.Alphas import *
from QuantConnect.Algorithm.Framework.Portfolio import *
from QuantConnect.Algorithm.Framework.Selection import *
from Alphas.ConstantAlphaModel import ConstantAlphaModel
from Selection.OptionUniverseSelectionModel import OptionUniverseSelectionModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from Risk.NullRiskManagementModel import NullRiskManagementModel
from datetime import date, timedelta

### <summary>
### Basic template options framework algorithm uses framework components
### to define an algorithm that trades options.
### </summary>
class BasicTemplateOptionsFrameworkAlgorithm(QCAlgorithm):

    def Initialize(self):

        self.UniverseSettings.Resolution = Resolution.Minute

        self.SetStartDate(2019, 1, 1)
        self.SetEndDate(2019, 1, 31)
        self.SetCash(100000)

        # set framework models
        self.SetUniverseSelection(EarliestExpiringWeeklyAtTheMoneyPutOptionUniverseSelectionModel(self.SelectOptionChainSymbols))
        self.SetAlpha(LogAlphaModel())
        self.SetPortfolioConstruction(SingleSharePortfolioConstructionModel())
        self.SetExecution(ImmediateExecutionModel())
        self.SetRiskManagement(NullRiskManagementModel())


    def SelectOptionChainSymbols(self, utcTime):
        return [ Symbol.Create("SPY", SecurityType.Option, Market.USA) ]

class EarliestExpiringWeeklyAtTheMoneyPutOptionUniverseSelectionModel(OptionUniverseSelectionModel):
    '''Creates option chain universes that select only the earliest expiry ATM weekly put contract
    and runs a user defined optionChainSymbolSelector every day to enable choosing different option chains'''
    def __init__(self, select_option_chain_symbols):
        super().__init__(timedelta(1), select_option_chain_symbols)

    def Filter(self, filter):
        '''Defines the option chain universe filter'''
        return (filter.Strikes(-1, +1)
                      .Expiration(timedelta(0), timedelta(30))
                      .PutsOnly()
                      .OnlyApplyFilterAtMarketOpen())

class LogAlphaModel(AlphaModel):
    def __init__(self):
        self.Name = '{}'.format(self.__class__.__name__)


    def Update(self, algorithm, data):
        return []

    def OnSecuritiesChanged(self, algorithm, changes):
        '''Event fired each time the we add/remove securities from the data feed
        Args:
            algorithm: The algorithm instance that experienced the change in securities
            changes: The security additions and removals from the algorithm'''
        for added in changes.AddedSecurities:
            if added.Symbol.SecurityType == SecurityType.Option:
                algorithm.Debug("Added:{}, Underlying:{}, Strike:{}, Type: {}, Date:{}".format(
                    added.Symbol,
                    added.Symbol.ID.Underlying,
                    added.Symbol.ID.StrikePrice,
                    added.Symbol.ID.OptionRight,
                    added.Symbol.ID.Date))
        for removed in changes.RemovedSecurities:
            if removed.Symbol.SecurityType == SecurityType.Option:
                algorithm.Debug("Removed:{}, Underlying:{}, Strike:{}, Type: {}, Date:{}".format(
                    removed.Symbol,
                    removed.Symbol.ID.Underlying,
                    removed.Symbol.ID.StrikePrice,
                    removed.Symbol.ID.OptionRight,
                    removed.Symbol.ID.Date))

class SingleSharePortfolioConstructionModel(PortfolioConstructionModel):
    '''Portfolio construction model that sets target quantities to 1 for up insights and -1 for down insights'''
    def CreateTargets(self, algorithm, insights):
        targets = []
        for insight in insights:
            targets.append(PortfolioTarget(insight.Symbol, insight.Direction))
        return targets