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 OptionsUniverseSelectionModel import OptionsUniverseSelectionModel
from universe import getUniverse

class MultidimensionalVerticalShield(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2019, 3, 22)  # Set Start Date
        self.SetEndDate(2019, 3, 29) 
        self.SetCash(100000)  # Set Strategy Cash
        self.options = {}
        for ticker in getUniverse():
            self.options[ticker] = {}
            eq = self.AddEquity( ticker, Resolution.Minute)
            eq.SetDataNormalizationMode(DataNormalizationMode.Raw);
        
        self.SetUniverseSelection(OptionsUniverseSelectionModel(self.SelectOptionsSymbols))
        hourConsolidator = TradeBarConsolidator(timedelta(minutes=120))
        hourConsolidator.DataConsolidated += self.sellOptions
        self.AddEquity( "SPY" , Resolution.Minute )
        
        self.SubscriptionManager.AddConsolidator("SPY", hourConsolidator)
            
    #TODO remove from consolidator
    def sellOptions( self, sender, bar ):
        if len( self.options ) < 0: return
        for ticker in getUniverse():
            optionList = [*self.options[ ticker ].values()]
            optionCall = self.getOption( ticker, optionList, right = OptionRight.Call, distance = 0.01 )
            optionPut = self.getOption( ticker, optionList, right = OptionRight.Put, distance = -0.01 )
            self.Debug("%f, %f" % (optionCall.BidPrice, optionPut.BidPrice ))
            self.Debug('%s, Strike %d, ' % (optionCall.Symbol, optionCall.StrikePrice ))
            self.Debug('%s, Strike %d, ' % (optionPut.Symbol, optionPut.StrikePrice ))


    def getOption( self, ticker, optionList, right, distance = 0.05, farest = True ):
        bound = self.Securities[ ticker ].Price * ( 1 + distance )
        optionList = [i for i in optionList if i.Right == right ]
        sortedOptionList = sorted(
            optionList,
            key=lambda x: x.Expiry, reverse=farest
        )
        expectedExpiry = sortedOptionList[0].Expiry
        sortedOptionList = [ i for i in optionList if i.Expiry ==  expectedExpiry ]
        option = min( sortedOptionList, key = lambda x : abs( x.StrikePrice - bound ))
        return option

    def OnSecuritiesChanged(self, changes) :
        
        for change in changes.RemovedSecurities:
            if change.Type == SecurityType.Option:
                if change.Underlying == None:
                    underlying = str(change.Symbol).split( " " )[0]
                else:
                    underlying = str(change.Underlying)
                self.options[ underlying ].pop( change.Symbol )
        for change in changes.AddedSecurities:
            if change.Type == SecurityType.Option:
                if change.Underlying == None:
                    underlying = str(change.Symbol).split( " " )[0]
                else:
                    underlying = str(change.Underlying)
                self.options[ underlying ][ change.Symbol ] = change
        
    def OnData(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
            Arguments:
                data: Slice object keyed by symbol containing the stock data
        '''

        # if not self.Portfolio.Invested:
        #    self.SetHoldings("SPY", 1)

    def SelectOptionsSymbols(self, utcTime):
        return [ Symbol.Create(ticker, SecurityType.Option, Market.USA, f"?{ticker}") for ticker in getUniverse()  ]
from Selection.OptionUniverseSelectionModel import OptionUniverseSelectionModel
from datetime import date, timedelta

class OptionsUniverseSelectionModel(OptionUniverseSelectionModel):
    def __init__(self, select_option_chain_symbols):
        super().__init__(timedelta(1), select_option_chain_symbols)

    def Filter(self, filter):
        ## Define options filter -- strikes +/- 3 and expiry between 0 and 180 days away
        return (filter.Strikes(-20, +20)
                      .Expiration(timedelta(0), timedelta(30)))
def getUniverse():
    #return ['SPY','AAPL','NFLX','GOOG','WMT', 'BABA','FB']#,'UVXY']
    return [ 'SPY' ]
# Your New Python File