Esempio n. 1
0
    def testUpdatePortfolioRiskManagementHoldToExpiration(self):
        """Tests that the position is removed from the portfolio when expiration occurs."""
        # Create a new position in addition to the default self.strangleObj position.
        startingCapital = decimal.Decimal(1000000)
        maxCapitalToUse = 0.5
        maxCapitalToUsePerTrade = 0.25
        portfolioObj = portfolio.Portfolio(startingCapital, maxCapitalToUse,
                                           maxCapitalToUsePerTrade)

        # Add first position to the portfolio
        event = signalEvent.SignalEvent()
        event.createEvent([self.strangleObj, self.riskManagement])
        portfolioObj.onSignal(event)

        putOpt = put.Put(underlyingTicker='SPX',
                         underlyingPrice=decimal.Decimal(2800.00),
                         strikePrice=decimal.Decimal(2700),
                         delta=-0.16,
                         gamma=0.01,
                         theta=0.02,
                         vega=0.03,
                         dateTime=datetime.datetime.strptime(
                             '01/01/2021', "%m/%d/%Y"),
                         expirationDateTime=datetime.datetime.strptime(
                             '01/01/2021', "%m/%d/%Y"),
                         bidPrice=decimal.Decimal(8.00),
                         askPrice=decimal.Decimal(8.50),
                         tradePrice=decimal.Decimal(8.25))
        callOpt = call.Call(underlyingTicker='SPX',
                            underlyingPrice=decimal.Decimal(2800.00),
                            strikePrice=decimal.Decimal(3000),
                            delta=0.16,
                            gamma=0.01,
                            theta=0.02,
                            vega=0.03,
                            dateTime=datetime.datetime.strptime(
                                '01/01/2021', "%m/%d/%Y"),
                            expirationDateTime=datetime.datetime.strptime(
                                '01/01/2021', "%m/%d/%Y"),
                            bidPrice=decimal.Decimal(6.00),
                            askPrice=decimal.Decimal(6.50),
                            tradePrice=decimal.Decimal(6.25))
        strangleObj = strangle.Strangle(
            orderQuantity=1,
            callOpt=callOpt,
            putOpt=putOpt,
            buyOrSell=optionPrimitive.TransactionType.SELL)

        # Add second position to the portfolio.
        event = signalEvent.SignalEvent()
        event.createEvent([strangleObj, self.riskManagement])
        portfolioObj.onSignal(event)

        # Update the portfolio, which should remove the second event. We do not change the prices of the putOpt or callOpt.
        testOptionChain = [callOpt, putOpt]
        event = tickEvent.TickEvent()
        event.createEvent(testOptionChain)
        portfolioObj.updatePortfolio(event)
        # Only one position should be left in the portfolio after removing the expired position.
        self.assertEqual(len(portfolioObj.activePositions), 1)
Esempio n. 2
0
    def testCheckForSignalSetMinBuyingPowerToForceMoreContracts(self):
        """Checks that more than one strangle is created if minBuyingPower is set."""
        callOption = self.optionChain.getData()[0]
        putOption = self.optionChain.getData()[1]
        # Set expiration to be monthly and less than self.minimumDTE.
        callOption.expirationDateTime = datetime.fromisoformat('2014-09-19')
        putOption.expirationDateTime = datetime.fromisoformat('2014-09-19')
        # Set put and call delta to be the desired values.
        putOption.delta = self.optPutDelta
        callOption.delta = self.optCallDelta
        # Set the bidPrice and askPrice such that the difference is less than self.maxBidAsk.
        putOption.bidPrice = 0.00
        putOption.askPrice = self.maxBidAsk
        callOption.bidPrice = 0.00
        callOption.askPrice = self.maxBidAsk
        testOptionChain = [callOption, putOption]

        # Set minimum buying power to force more strangles to be added.
        minBuyingPower = 20600  # two strangles in 'AAPL' for test data.
        curStrategy = strangleStrat.StrangleStrat(
            self.signalEventQueue, self.optCallDelta, self.maxCallDelta,
            self.optPutDelta, self.maxPutDelta, self.startDateTime,
            self.buyOrSell, self.underlyingTicker, self.orderQuantity,
            self.riskManagement, self.expCycle, self.optimalDTE,
            self.minimumDTE, self.minimumROC, self.minCredit, self.maxBidAsk,
            minBuyingPower)

        event = tickEvent.TickEvent()
        event.createEvent(testOptionChain)
        curStrategy.checkForSignal(event)
        strangleObj = self.signalEventQueue.get().getData()[0]
        self.assertEqual(strangleObj.getNumContracts(), 2)
Esempio n. 3
0
    def testUpdatePortfolio(self):
        """Tests the ability to update option values for a position in the portfolio."""
        # Create strangle event.
        event = signalEvent.SignalEvent()
        event.createEvent([self.strangleObj, self.riskManagement])

        # Create portfolio onSignal event, which adds the position to the portfolio.
        startingCapital = decimal.Decimal(1000000)
        maxCapitalToUse = 0.5
        maxCapitalToUsePerTrade = 0.5
        portfolioObj = portfolio.Portfolio(startingCapital, maxCapitalToUse,
                                           maxCapitalToUsePerTrade)
        portfolioObj.onSignal(event)

        # Next, create a strangle with the next days prices and update the portfolio values.
        putOpt = put.Put(underlyingTicker='SPX',
                         underlyingPrice=decimal.Decimal(2786.24),
                         strikePrice=decimal.Decimal(2690),
                         delta=-0.16,
                         gamma=0.01,
                         theta=0.02,
                         vega=0.03,
                         dateTime=datetime.datetime.strptime(
                             '01/02/2021', "%m/%d/%Y"),
                         expirationDateTime=datetime.datetime.strptime(
                             '01/20/2021', "%m/%d/%Y"),
                         bidPrice=decimal.Decimal(6.45),
                         askPrice=decimal.Decimal(6.50),
                         tradePrice=decimal.Decimal(6.475))
        callOpt = call.Call(underlyingTicker='SPX',
                            underlyingPrice=decimal.Decimal(2786.24),
                            strikePrice=decimal.Decimal(2855),
                            delta=0.16,
                            gamma=0.01,
                            theta=0.02,
                            vega=0.03,
                            dateTime=datetime.datetime.strptime(
                                '01/02/2021', "%m/%d/%Y"),
                            expirationDateTime=datetime.datetime.strptime(
                                '01/20/2021', "%m/%d/%Y"),
                            bidPrice=decimal.Decimal(4.20),
                            askPrice=decimal.Decimal(4.40),
                            tradePrice=decimal.Decimal(4.30))

        # Create tick event and update portfolio values.
        testOptionChain = [callOpt, putOpt]
        event = tickEvent.TickEvent()
        event.createEvent(testOptionChain)
        portfolioObj.updatePortfolio(event)

        # Check that the new portfolio values are correct (e.g., buying power, total delta, total gamma, etc).
        self.assertAlmostEqual(portfolioObj.totalBuyingPower,
                               decimal.Decimal(63310.0))
        self.assertAlmostEqual(portfolioObj.totalVega, 0.06)
        self.assertAlmostEqual(portfolioObj.totalDelta, 0.0)
        self.assertAlmostEqual(portfolioObj.totalGamma, 0.02)
        self.assertAlmostEqual(portfolioObj.totalTheta, 0.04)
        self.assertAlmostEqual(portfolioObj.netLiquidity,
                               decimal.Decimal(1000200.0))
Esempio n. 4
0
 def testUpdateWithOptimalOptionNotMonthlyExpiration(self):
     """Tests that no signal event is created if we do not have a monthly expiration."""
     # These options do not have a monthly expiration.
     testOptionChain = [
         self.optionChain.getData()[0],
         self.optionChain.getData()[1]
     ]
     event = tickEvent.TickEvent()
     event.createEvent(testOptionChain)
     self.curStrategy.checkForSignal(event)
     self.assertEqual(self.signalEventQueue.qsize(), 0)
Esempio n. 5
0
 def testUpdateWithOptimalOptionDTELessThanMinimum(self):
     """Tests that no signal event is created if the number of days to expiration is less than minimum."""
     callOption = self.optionChain.getData()[0]
     putOption = self.optionChain.getData()[1]
     # Modify expiration to be a monthly expiration, but set the number of days such that it is less than
     # self.minimumDTE.
     callOption.expirationDateTime = datetime.fromisoformat('2014-08-15')
     putOption.expirationDateTime = datetime.fromisoformat('2014-08-15')
     testOptionChain = [callOption, putOption]
     event = tickEvent.TickEvent()
     event.createEvent(testOptionChain)
     self.curStrategy.checkForSignal(event)
     self.assertEqual(self.signalEventQueue.qsize(), 0)
Esempio n. 6
0
 def testUpdateWithOptimalOptionDeltaGreaterThanMaxPutDelta(self):
     """Tests that no signal event is created if the put delta is greater than the max delta."""
     callOption = self.optionChain.getData()[0]
     putOption = self.optionChain.getData()[1]
     # Set expiration to be monthly and less than self.minimumDTE.
     callOption.expirationDateTime = datetime.fromisoformat('2014-09-19')
     putOption.expirationDateTime = datetime.fromisoformat('2014-09-19')
     # Modify delta of put option to be greater than max delta.
     putOption.delta = self.maxPutDelta * 2
     callOption.delta = self.optCallDelta
     testOptionChain = [callOption, putOption]
     event = tickEvent.TickEvent()
     event.createEvent(testOptionChain)
     self.curStrategy.checkForSignal(event)
     self.assertEqual(self.signalEventQueue.qsize(), 0)
Esempio n. 7
0
    def testUpdateWithOptimalOptionCurrentOptionHasFurtherDTE(self):
        """Tests second put[3] and call[2] options are not chosen as the optimal options because their deltas are further
    from the requested delta. All put and call options have the same expiration."""
        callOptionOptimalDelta = self.optionChain.getData()[0]
        callOptionNonOptimalDelta = self.optionChain.getData()[2]
        putOptionOptimalDelta = self.optionChain.getData()[1]
        putOptionNonOptimalDelta = self.optionChain.getData()[3]

        # Set expiration to be the same, monthly, and less than self.minimumDTE.
        callOptionOptimalDelta.expirationDateTime = datetime.fromisoformat(
            '2014-09-19')
        callOptionNonOptimalDelta.expirationDateTime = datetime.fromisoformat(
            '2014-09-19')
        putOptionOptimalDelta.expirationDateTime = datetime.fromisoformat(
            '2014-09-19')
        putOptionNonOptimalDelta.expirationDateTime = datetime.fromisoformat(
            '2014-09-19')

        # Set put and call delta. We use these delta values to check that the options with the optimal DTE
        # were chosen.
        callOptionOptimalDelta.delta = self.optCallDelta
        callOptionNonOptimalDelta.delta = 0.05
        putOptionOptimalDelta.delta = self.optPutDelta
        putOptionNonOptimalDelta.delta = -0.1

        # Set the bidPrice and askPrice such that the difference is less than self.maxBidAsk.
        callOptionOptimalDelta.bidPrice = 0.00
        callOptionOptimalDelta.askPrice = self.maxBidAsk
        callOptionNonOptimalDelta.bidPrice = 0.00
        callOptionNonOptimalDelta.askPrice = self.maxBidAsk
        putOptionOptimalDelta.bidPrice = 0.00
        putOptionOptimalDelta.askPrice = self.maxBidAsk
        putOptionNonOptimalDelta.bidPrice = 0.00
        putOptionNonOptimalDelta.askPrice = self.maxBidAsk

        testOptionChain = [
            callOptionOptimalDelta, putOptionOptimalDelta,
            callOptionNonOptimalDelta, putOptionNonOptimalDelta
        ]
        event = tickEvent.TickEvent()
        event.createEvent(testOptionChain)
        self.curStrategy.checkForSignal(event)
        strangleObj = self.signalEventQueue.get().getData()[0]
        self.assertAlmostEqual(
            strangleObj.getDelta(),
            callOptionOptimalDelta.delta + putOptionOptimalDelta.delta)
Esempio n. 8
0
    def testUpdateWithOptimalOptionChooseCloserExpiration(self):
        """Tests that we choose the option with the expiration date closer to self.optimalDTE."""
        callOptionNonOptimalDTE = self.optionChain.getData()[0]
        callOptionOptimalDTE = self.optionChain.getData()[2]
        putOptionNonOptimalDTE = self.optionChain.getData()[1]
        putOptionOptimalDTE = self.optionChain.getData()[3]

        # Set expiration to be monthly and less than self.minimumDTE.
        callOptionNonOptimalDTE.expirationDateTime = datetime.fromisoformat(
            '2014-10-17')
        callOptionOptimalDTE.expirationDateTime = datetime.fromisoformat(
            '2014-09-19')
        putOptionNonOptimalDTE.expirationDateTime = datetime.fromisoformat(
            '2014-10-17')
        putOptionOptimalDTE.expirationDateTime = datetime.fromisoformat(
            '2014-09-19')

        # Set put and call delta. We use these delta values to check that the options with the optimal DTE
        # were chosen.
        callOptionNonOptimalDTE.delta = self.optCallDelta
        callOptionOptimalDTE.delta = 0.20
        putOptionNonOptimalDTE.delta = self.optPutDelta
        putOptionOptimalDTE.delta = -0.10

        # Set the bidPrice and askPrice such that the difference is less than self.maxBidAsk.
        callOptionNonOptimalDTE.bidPrice = 0.00
        callOptionNonOptimalDTE.askPrice = self.maxBidAsk
        callOptionOptimalDTE.bidPrice = 0.00
        callOptionOptimalDTE.askPrice = self.maxBidAsk
        putOptionNonOptimalDTE.bidPrice = 0.00
        putOptionNonOptimalDTE.askPrice = self.maxBidAsk
        putOptionOptimalDTE.bidPrice = 0.00
        putOptionOptimalDTE.askPrice = self.maxBidAsk

        testOptionChain = [
            callOptionNonOptimalDTE, putOptionNonOptimalDTE,
            callOptionOptimalDTE, putOptionOptimalDTE
        ]
        event = tickEvent.TickEvent()
        event.createEvent(testOptionChain)
        self.curStrategy.checkForSignal(event)
        strangleObj = self.signalEventQueue.get().getData()[0]
        self.assertAlmostEqual(
            strangleObj.getDelta(),
            callOptionOptimalDTE.delta + putOptionOptimalDTE.delta)
Esempio n. 9
0
 def testCheckForSignalCallAndPutWithDifferentExpirations(self):
     """Tests that no signal event is created if put and call options have different expirations."""
     callOption = self.optionChain.getData()[0]
     putOption = self.optionChain.getData()[1]
     # Set expiration to be monthly and less than self.minimumDTE.
     callOption.expirationDateTime = datetime.fromisoformat('2014-09-19')
     putOption.expirationDateTime = datetime.fromisoformat('2014-10-17')
     # Set put and call delta to be the desired values.
     putOption.delta = self.optPutDelta
     callOption.delta = self.optCallDelta
     # Set the bidPrice and askPrice such that the difference is less than self.maxBidAsk.
     putOption.bidPrice = 0.00
     putOption.askPrice = self.maxBidAsk
     callOption.bidPrice = 0.00
     callOption.askPrice = self.maxBidAsk
     testOptionChain = [callOption, putOption]
     event = tickEvent.TickEvent()
     event.createEvent(testOptionChain)
     self.curStrategy.checkForSignal(event)
     self.assertEqual(self.signalEventQueue.qsize(), 0)
Esempio n. 10
0
 def getNextTick(self) -> bool:
     """Used to get the next available piece of data from the data source. For the CSV example, this would likely be the
 next row for a stock or group of rows for an option chain.
 :return True / False indicating if there is data available.
 """
     if self.__dataConfig[
             self.__dataProvider]['data_source_type'] == 'options':
         # Get optionChain as a dataframe.
         optionChain = self.__getOptionChain()
         if len(optionChain.index) == 0:
             # No more data available.
             return False
         # Convert optionChain from a dataframe to Option class objects.
         optionChainObjs = self.__createBaseType(optionChain)
         # Create tick event with option chain objects.
         event = tickEvent.TickEvent()
         event.createEvent(optionChainObjs)
         self.__eventQueue.put(event)
         return True
     elif self.__dataConfig[
             self.__dataProvider]['data_source_type'] == 'stocks':
         pass
Esempio n. 11
0
    def testPortfolioWithExpirationManagement(self):
        """Put on a strangle; update portfolio values, and then manage the strangle when the daysBeforeClosing
        threshold has been met.
        """
        # Create portfolio object.
        portfolioObj = portfolio.Portfolio(self.startingCapital,
                                           self.maxCapitalToUse,
                                           self.maxCapitalToUsePerTrade)

        # Set up date / time formats.
        local = pytz.timezone('US/Eastern')

        # Convert time zone of data 'US/Eastern' to UTC time.
        expDate = datetime.datetime.strptime("02/20/18", "%m/%d/%y")
        expDate = local.localize(expDate, is_dst=None)
        expDate = expDate.astimezone(pytz.utc)

        # Convert time zone of data 'US/Eastern' to UTC time.
        curDate = datetime.datetime.strptime("02/02/18", "%m/%d/%y")
        curDate = local.localize(curDate, is_dst=None)
        curDate = curDate.astimezone(pytz.utc)

        # Add first position to the portfolio.
        putOpt = put.Put('SPX',
                         2690,
                         0.15,
                         expDate,
                         underlyingPrice=2786.24,
                         bidPrice=7.45,
                         askPrice=7.45,
                         optionSymbol="01",
                         tradePrice=7.45,
                         dateTime=curDate)
        callOpt = call.Call('SPX',
                            2855,
                            -0.15,
                            expDate,
                            underlyingPrice=2786.24,
                            bidPrice=5.20,
                            askPrice=5.20,
                            optionSymbol="02",
                            tradePrice=5.20,
                            dateTime=curDate)

        # Create Strangle.
        orderQuantity = 1
        daysBeforeClosing = 5
        strangleObj = strangle.Strangle(orderQuantity, callOpt, putOpt, "SELL",
                                        daysBeforeClosing)

        # Create signal event.
        event = signalEvent.SignalEvent()
        event.createEvent(strangleObj)

        # Create portfolio onSignal event, which adds the position to the portfolio.
        portfolioObj.onSignal(event)

        # Check that the position was added to the portfolio.
        self.assertEqual(len(portfolioObj.getPositions()), 1)

        # Change the time to be within five days from the DTE, which should cause the position to be closed / deleted
        # from the portfolio.
        curDate = datetime.datetime.strptime("02/19/18", "%m/%d/%y")
        curDate = local.localize(curDate, is_dst=None)
        curDate = curDate.astimezone(pytz.utc)

        newOptionObjs = []
        putOpt = put.Put('SPX',
                         2690,
                         0.15,
                         expDate,
                         underlyingPrice=2786.24,
                         bidPrice=7.45,
                         askPrice=7.45,
                         optionSymbol="01",
                         tradePrice=7.45,
                         dateTime=curDate)
        newOptionObjs.append(putOpt)
        callOpt = call.Call('SPX',
                            2855,
                            -0.15,
                            expDate,
                            underlyingPrice=2786.24,
                            bidPrice=5.20,
                            askPrice=5.20,
                            optionSymbol="02",
                            tradePrice=5.20,
                            dateTime=curDate)
        newOptionObjs.append(callOpt)

        newEvent = tickEvent.TickEvent()
        newEvent.createEvent(newOptionObjs)
        portfolioObj.updatePortfolio(newEvent)

        # Check that the position was managed / deleted from the portfolio.
        self.assertEqual(len(portfolioObj.getPositions()), 0)
Esempio n. 12
0
    def testPortfolioPositionRemoveManagement(self):
        """Test that we can remove a managed position from the portfolio without affecting any of the other positions
        in the portfolio.
        """

        # Create portfolio object.
        portfolioObj = portfolio.Portfolio(self.startingCapital,
                                           self.maxCapitalToUse,
                                           self.maxCapitalToUsePerTrade)

        # Add first position to the portfolio.
        putOpt = put.Put('SPX',
                         2690,
                         0.15,
                         34,
                         underlyingPrice=2786.24,
                         bidPrice=7.45,
                         askPrice=7.45,
                         optionSymbol="01",
                         tradePrice=7.45)
        callOpt = call.Call('SPX',
                            2855,
                            -0.15,
                            34,
                            underlyingPrice=2786.24,
                            bidPrice=5.20,
                            askPrice=5.20,
                            optionSymbol="02",
                            tradePrice=5.20)

        # Create Strangle.
        orderQuantity = 1
        profitTargetPercent = 0.5
        strangleObj = strangle.Strangle(
            orderQuantity,
            callOpt,
            putOpt,
            "SELL",
            profitTargetPercent=profitTargetPercent)

        # Create signal event.
        event = signalEvent.SignalEvent()
        event.createEvent(strangleObj)

        # Create portfolio onSignal event, which adds the position to the portfolio.
        portfolioObj.onSignal(event)

        # Add second position to the portfolio.
        putOpt = put.Put('AAPL',
                         140,
                         0.15,
                         34,
                         underlyingPrice=150,
                         bidPrice=5.15,
                         askPrice=5.15,
                         optionSymbol="03",
                         tradePrice=5.15)
        callOpt = call.Call('APPL',
                            160,
                            -0.15,
                            34,
                            underlyingPrice=150,
                            bidPrice=3.20,
                            askPrice=3.20,
                            optionSymbol="04",
                            tradePrice=3.20)

        strangleObj = strangle.Strangle(
            orderQuantity,
            callOpt,
            putOpt,
            "SELL",
            profitTargetPercent=profitTargetPercent)

        # Create signal event.
        event = signalEvent.SignalEvent()
        event.createEvent(strangleObj)

        # Create portfolio onSignal event, which adds the position to the portfolio.
        portfolioObj.onSignal(event)

        # Add a third position to the portfolio.
        putOpt = put.Put('SPY',
                         240,
                         0.15,
                         34,
                         underlyingPrice=280,
                         bidPrice=4.15,
                         askPrice=4.15,
                         optionSymbol="05",
                         tradePrice=4.15)
        callOpt = call.Call('SPY',
                            300,
                            -0.15,
                            34,
                            underlyingPrice=280,
                            bidPrice=2.20,
                            askPrice=2.20,
                            optionSymbol="06",
                            tradePrice=2.20)

        strangleObj = strangle.Strangle(
            orderQuantity,
            callOpt,
            putOpt,
            "SELL",
            profitTargetPercent=profitTargetPercent)

        # Create signal event.
        event = signalEvent.SignalEvent()
        event.createEvent(strangleObj)

        # Create portfolio onSignal event, which adds the position to the portfolio.
        portfolioObj.onSignal(event)

        # For the second position in the portfolio, make the option prices less than 50% of the trade price, which
        # should cause the position to be closed / deleted from the portfolio.
        newOptionObjs = []
        putOpt = put.Put('SPX',
                         2690,
                         0.15,
                         34,
                         underlyingPrice=2786.24,
                         bidPrice=7.45,
                         askPrice=7.45,
                         optionSymbol="01",
                         tradePrice=7.45)
        newOptionObjs.append(putOpt)
        callOpt = call.Call('SPX',
                            2855,
                            -0.15,
                            34,
                            underlyingPrice=2786.24,
                            bidPrice=5.20,
                            askPrice=5.20,
                            optionSymbol="02",
                            tradePrice=5.20)
        newOptionObjs.append(callOpt)
        putOpt = put.Put('AAPL',
                         140,
                         0.15,
                         34,
                         underlyingPrice=150,
                         bidPrice=2.15,
                         askPrice=2.15,
                         optionSymbol="03")
        newOptionObjs.append(putOpt)
        callOpt = call.Call('APPL',
                            160,
                            -0.15,
                            34,
                            underlyingPrice=150,
                            bidPrice=1.20,
                            askPrice=1.20,
                            optionSymbol="04")
        newOptionObjs.append(callOpt)
        putOpt = put.Put('SPY',
                         240,
                         0.15,
                         34,
                         underlyingPrice=280,
                         bidPrice=4.15,
                         askPrice=4.15,
                         optionSymbol="05",
                         tradePrice=4.15)
        newOptionObjs.append(putOpt)
        callOpt = call.Call('SPY',
                            300,
                            -0.15,
                            34,
                            underlyingPrice=280,
                            bidPrice=2.20,
                            askPrice=2.20,
                            optionSymbol="06",
                            tradePrice=2.20)
        newOptionObjs.append(callOpt)

        newEvent = tickEvent.TickEvent()
        newEvent.createEvent(newOptionObjs)
        portfolioObj.updatePortfolio(newEvent)

        # Check that the first position is the SPX position, and the second position is the SPY position, i.e., the
        # AAPL position should have been managed / removed.
        positions = portfolioObj.getPositions()
        callPos0 = positions[0].getCallOption()
        callPos1 = positions[1].getCallOption()

        self.assertEqual(callPos0.getUnderlyingTicker(), 'SPX')
        self.assertEqual(callPos1.getUnderlyingTicker(), 'SPY')
        self.assertEqual(len(positions), 2)
Esempio n. 13
0
    def getOptionChain(self):
        """
        Used to get the option chain data for the underlying.
        The option chain consists of all of the puts and calls
        at all strikes currently listed for the underlying.
        Returns true/false depending on whether or not we successfully
        were able to get the option chain data.  On success, the
        the rows of the option chain are converted into option objects,
        and the objects are put into the eventQueue as one event.
        """

        # Attempt to get option chain from CSV -- the way we determine
        # which strikes / data belong to the option chain for the current
        # tick is by keeping track of the time/date.

        # Used to store all rows in current option chain.
        optionChain = []

        # Used to store objects created for each row of the option chain
        optionChainObjs = []

        # Different data providers will have to be handled differently.
        if self.__dataProvider == "iVolatility":

            # Get the first N rows with the same time/date.
            # To do this, we get the time/data from the first row, and then
            # we add to this any rows with the same date/time.

            # Handle first row -- add to optionChain.
            try:
                optionChain.append(self.__dataFrame.iloc[self.__curRow])
                self.__curTimeDate = self.__dataFrame['date'].iloc[
                    self.__curRow]
                self.__curRow += 1
            except:
                # Could not get the current row if we end up here; try chunking to get more data.
                try:
                    self.__dataFrame = self.__dataReader.get_chunk(
                        self.__chunkSize)
                    self.__curRow = 0
                    optionChain.append(self.__dataFrame.iloc[self.__curRow])
                    self.__curTimeDate = self.__dataFrame['date'].iloc[
                        self.__curRow]
                    self.__curRow += 1
                except:
                    return False

            # TODO:  replace this while loop with something more efficient --
            # For example, can select all dates from dataframe and then iterate
            # through them; we would need to keep track of the curRow still so we
            # can get the next option chain.  We do it in this manner since it
            # seems that it would be faster if we had a HUGE CSV and tried to
            # do a bunch of groups for different dates.
            while 1:
                try:
                    curTimeDate = self.__dataFrame['date'].iloc[self.__curRow]
                except:
                    # Try chunking to get more data since we couldn't get current row.
                    try:
                        self.__dataFrame = self.__dataReader.get_chunk(
                            self.__chunkSize)
                        self.__curRow = 0
                        curTimeDate = self.__dataFrame['date'].iloc[
                            self.__curRow]
                    except:
                        break

                if curTimeDate == self.__curTimeDate:
                    optionChain.append(self.__dataFrame.iloc[self.__curRow])
                    self.__curRow += 1
                else:
                    break

            # Convert option chain to base types (calls, puts).
            for row in optionChain:
                currentObj = self.createBaseType(row)
                # Make sure currentObj is not None.
                if currentObj:
                    optionChainObjs.append(currentObj)

            # Create event and add to queue
            event = tickEvent.TickEvent()
            event.createEvent(optionChainObjs)
            self.__eventQueue.put(event)

            return True
Esempio n. 14
0
 def testCreateTickEvent(self):
     """Tests that a signal event is successfully created."""
     tickObj = tickEvent.TickEvent()
     # Check that the data reference attribute is set to None since there has been no data passed.
     self.assertEqual(tickObj.getData(), None)
     self.assertEqual(tickObj.type, event.EventTypes.TICK)