Exemplo n.º 1
0
    def test_get_price(self):
        call = Option('call', TSLA, 420, datetime(2020, 12, 4))
        call.price = 420
        chain = OptionChain(TSLA, datetime.now())
        chain.add_option(call)

        self.assertEqual(420, chain.get_price(call))
Exemplo n.º 2
0
    def test_eval_no_security(self):
        call = Option('call', TSLA, 500, datetime(2020, 12, 28))
        put = Option('put', TSLA, 500, datetime(2020, 12, 28))
        port = Portfolio(50000, {TSLA: 100, call: 1, put: 1})
        te = TradingEngine([port])

        te.eval({Security('GOOG'): 650}, datetime(2020, 12, 28))

        self.assertEqual(50000, port.cash)
        self.assertEqual(100, port.securities[TSLA])
Exemplo n.º 3
0
    def test_eval(self):
        call = Option('call', TSLA, 400, datetime(2020, 12, 28))
        put = Option('put', TSLA, 420, datetime(2020, 12, 28))
        port = Portfolio(50000, {TSLA: 200, call: -2, put: -2})
        te = TradingEngine([port])

        te.eval({TSLA: 410}, datetime(2020, 12, 28))

        self.assertEqual(50000 + (40000 * 2) - (42000 * 2), port.cash)
        self.assertEqual(200, port.securities[TSLA])
Exemplo n.º 4
0
    def test_check_and_invoke_contracts(self):
        call = Option('call', TSLA, 420, datetime(2021, 4, 20))
        call.price = 35
        p = Portfolio(securities={call: -1})
        ss = StockSplitHandler(Path('tests/test_data/TSLA/splits.csv'), TSLA)

        ss.check_and_invoke(p, datetime(2020, 8, 31))
        new_call = Option('call', TSLA, 420 / 5, datetime(2021, 4, 20))

        contract = next(iter(p.securities.keys()))
        self.assertEqual(1, len(p.securities))
        self.assertEqual(-1 * 5, p.securities[new_call])
        self.assertEqual(7, contract.price)
        self.assertEqual(420 / 5, contract.strike)
Exemplo n.º 5
0
    def test_expire_and_assign(self):
        call = Option('call', TSLA, 500, datetime(2020, 12, 28))
        port = Portfolio(0, {TSLA: 100})
        te = TradingEngine([port])

        te.sell_contract(port, call, 10)
        te.eval({TSLA: 400}, datetime(2020, 12, 28))

        call = Option('call', TSLA, 500, datetime(2021, 1, 15))
        te.sell_contract(port, call, 5)
        te.eval({TSLA: 600}, datetime(2021, 1, 15))

        self.assertEqual(1000 + 500 + 50000, port.cash)
        self.assertEqual(0, port.securities[TSLA])
        self.assertEqual(0, port.contracts()[call])
Exemplo n.º 6
0
    def test_otm(self):
        security = Security('TSLA')
        security.add_quote(Quote(420, datetime.now()))
        o1 = Option('call', security, 500, datetime(2020, 4, 20))
        o2 = Option('put', security, 300, datetime(2020, 4, 20))
        o3 = Option('call', security, 100, datetime(2020, 4, 20))  # ITM

        chain = OptionChain(security, datetime.now())
        chain.add_option(o1)
        chain.add_option(o2)
        chain.add_option(o3)

        calls, puts = chain.otm(datetime(2020, 4, 20)).values()
        self.assertEqual(1, len(calls))
        self.assertEqual(1, len(puts))
Exemplo n.º 7
0
 def test_option_itm(self):
     security = Security('TSLA')
     call = Option('call', security, 420, datetime(2020, 12, 4))
     put = Option('put', security, 420, datetime(2020, 12, 4))
     self.assertTrue(call.itm(500))
     self.assertFalse(call.itm(400))
     self.assertTrue(put.itm(400))
     self.assertFalse(put.itm(500))
Exemplo n.º 8
0
    def test_sell_too_many_contracts(self):
        call = Option('call', TSLA, 500, datetime(2020, 12, 28))
        port = Portfolio(0, {TSLA: 100})
        te = TradingEngine([port])

        te.sell_contract(port, call, 10)
        self.assertRaises(Exception, te.sell_contract, port, call, 10)
Exemplo n.º 9
0
    def test_release_collateral(self):
        call = Option('call', TSLA, 500, datetime(2020, 12, 28))
        port = Portfolio(50000, {TSLA: 100})
        te = TradingEngine([port])

        # sell a contract to start, putting up 100 shares as collateral
        te.sell_contract(port, call, 10)
        self.assertEqual(-1, port.securities[call])
        self.assertEqual(100, port.collateral[TSLA])

        # buy back the contract, eliminating the obligation
        te.buy_contract(port, call, 10)
        self.assertEqual(0, port.securities[call])
        self.assertEqual(0, port.collateral[TSLA])

        # go long instead, purchasing a call
        te.buy_contract(port, call, 10)
        self.assertEqual(1, port.securities[call])
        self.assertEqual(0, port.collateral[TSLA])

        # close that long call
        te.sell_contract(port, call, 10)
        self.assertEqual(0, port.securities[call])
        self.assertEqual(0, port.collateral[TSLA])

        # sell an option to go short again
        te.sell_contract(port, call, 10)
        self.assertEqual(-1, port.securities[call])
        self.assertEqual(100, port.collateral[TSLA])
Exemplo n.º 10
0
 def _parse_chain(self, date, security, contracts):
     chain = OptionChain(security, date)
     for contract in contracts:
         fields = contract.split(' ')
         match = re.match(r'(\d+)(c|p)(\d+\.\d*)', fields[0])
         expiration = datetime.strptime(match[1], '%y%m%d')
         direction = 'call' if match[2] == 'c' else 'put'
         strike = float(match[3])
         price = float(fields[1])
         delta = float(fields[2])
         theta = float(fields[3])
         option = Option(direction, security, strike, expiration)
         option.price = price
         option.delta = delta
         option.theta = theta
         chain.add_option(option)
     return chain
Exemplo n.º 11
0
    def test_sell_contract(self):
        call = Option('call', TSLA, 500, datetime(2020, 12, 28))
        port = Portfolio(0, {TSLA: 100})
        te = TradingEngine([port])

        te.sell_contract(port, call, 10)

        self.assertEqual(1000, port.cash)
        self.assertEqual(-1, port.securities[call])
Exemplo n.º 12
0
    def test_option_expiration(self):
        call = Option('call', TSLA, 500, datetime(2020, 12, 28))
        port = Portfolio(0, {TSLA: 100})
        te = TradingEngine([port])

        te.sell_contract(port, call, 10)
        te.eval({TSLA: 400}, datetime(2020, 12, 28))

        self.assertFalse(port.contracts())
        self.assertEqual(0, port.collateral[TSLA])
Exemplo n.º 13
0
    def test_assign_put(self):
        put = Option('put', TSLA, 500, datetime(2020, 12, 28))
        port = Portfolio(70000, {TSLA: 12, put: -1})
        port.collateral[TSLA] = 100
        te = TradingEngine()

        te.assign(port, put, -1)

        self.assertEqual(70_000 - 50_000, port.cash)
        self.assertEqual(112, port.securities[TSLA])
        self.assertEqual(0, port.securities[put])
        self.assertEqual(0, port.collateral[TSLA])
Exemplo n.º 14
0
    def test_close_short_call(self):
        path = Path('tests/test_data/normalized/TSLA')
        training = pd.read_csv(path / 'training.csv',
                               parse_dates=['date'],
                               date_parser=from_small_date)
        call = Option('call', TSLA, 420, datetime(2020, 7, 17))
        portfolio = Portfolio(cash=133535, securities={call: -1})

        sim = Simulator(TSLA, portfolio, path, training)
        sim._buy(datetime(2020, 7, 14))

        self.assertEqual(0, portfolio.securities[call])
        self.assertEqual(0, portfolio.cash)
Exemplo n.º 15
0
    def test_assign_call(self):
        call = Option('call', TSLA, 500, datetime(2020, 12, 28))
        secs = {TSLA: 100, call: -1}
        port = Portfolio(420, secs)
        port.collateral[TSLA] = 100
        te = TradingEngine()

        te.assign(port, call, -1)

        self.assertEqual(420 + 50000, port.cash)
        self.assertEqual(0, port.securities[TSLA])
        self.assertEqual(0, port.securities[call])
        self.assertEqual(0, port.collateral[TSLA])
Exemplo n.º 16
0
 def _parse_option(self, security, exp_dt, json):
     direction = json['optionType'].lower()
     strike = json['strikePrice']
     expiration = datetime.strptime(exp_dt, '%Y-%m-%d')
     option = Option(direction, security, strike, expiration)
     option.delta = self._scrub_value(json['OptionGreeks']['delta'])
     option.theta = self._scrub_value(json['OptionGreeks']['theta'])
     option.vega = self._scrub_value(json['OptionGreeks']['vega'])
     option.iv = self._scrub_value(json['OptionGreeks']['iv'])
     option.price = self._scrub_value(json['lastPrice'])
     return option
Exemplo n.º 17
0
 def _parse_option(self, security, exp_dt, json):
     type = json['optionType'].lower()
     strike = json['strikePrice']
     expiration = datetime.strptime(exp_dt, '%Y-%m-%d')
     option = Option(type, security, strike, expiration)
     option.delta = json['OptionGreeks']['delta']
     option.theta = json['OptionGreeks']['theta']
     option.vega = json['OptionGreeks']['vega']
     option.iv = json['OptionGreeks']['iv']
     option.price = json['lastPrice']
     return option
Exemplo n.º 18
0
    def test_expire_without_close_on_expiration(self):
        path = Path('tests/test_data/normalized/TSLA')
        training = pd.read_csv(path / 'training.csv',
                               parse_dates=['date'],
                               date_parser=from_small_date)
        call = Option('call', TSLA, 2800, datetime(2020, 7, 24))
        portfolio = Portfolio(cash=0, securities={TSLA: 100, call: -1})
        portfolio.collateral = {TSLA: 100}
        sim = Simulator(TSLA, portfolio, path, training)
        net = BuyAndHoldNet()

        sim.simulate(net, datetime(2020, 7, 23), datetime(2020, 8, 3))

        self.assertEqual(0, portfolio.securities.get(call, 0))
Exemplo n.º 19
0
    def test_calculate_fitness(self):
        path = Path('tests/test_data/normalized/TSLA')
        training = pd.read_csv(path / 'training.csv',
                               parse_dates=['date'],
                               date_parser=from_small_date)
        call = Option('call', TSLA, 420, datetime(2020, 9, 11))
        portfolio = Portfolio(cash=10, securities={TSLA: 100, call: -1})

        sim = Simulator(TSLA, portfolio, path, training)
        actual = sim._calculate_fitness(0.2990607757568724,
                                        datetime(2020, 9, 8))  # 420.28
        # starting cash + value of shares - call obligation - buy-and-hold value
        expected = 10 + (420.28 * 100) - (1.44 * 100) - (420.28 * 100)
        self.assertAlmostEqual(expected, actual, places=2)
Exemplo n.º 20
0
    def test_exercise_call(self):
        call = Option('call', TSLA, 500, datetime(2020, 12, 28))
        port = Portfolio(51000, {})
        te = TradingEngine([port])

        te.buy_contract(port, call, 10)
        self.assertEqual(51000 - 1000, port.cash)
        self.assertEqual(1, port.contracts()[call])

        te.eval({TSLA: 600}, datetime(2020, 12, 28))

        self.assertEqual(0, port.cash)
        self.assertEqual(100, port.securities[TSLA])
        self.assertEqual(0, port.securities[call])
Exemplo n.º 21
0
    def test_exercise_put(self):
        put = Option('put', TSLA, 500, datetime(2020, 12, 28))
        port = Portfolio(2000, {TSLA: 100})
        te = TradingEngine([port])

        te.buy_contract(port, put, 10)
        self.assertEqual(2000 - 1000, port.cash)
        self.assertEqual(1, port.contracts()[put])

        te.eval({TSLA: 400}, datetime(2020, 12, 28))

        self.assertEqual(2000 - 1000 + 50000, port.cash)
        self.assertEqual(0, port.securities.get(TSLA, 0))
        self.assertEqual(0, port.securities[put])
Exemplo n.º 22
0
    def test_search(self):
        security = Security('TSLA')
        o1 = Option('call', security, 500, datetime(2020, 4, 1))
        o1.theta = -2.02
        o1.delta = 0.83
        o2 = Option('put', security, 300, datetime(2020, 4, 20))
        o2.theta = -0.16
        o2.delta = -0.34

        chain = OptionChain(security, datetime.now())
        chain.add_option(o1)
        chain.add_option(o2)

        result = chain.search(theta=-2, delta=0.8)
        assert o1.strike == result.strike
        result = chain.search(theta=-1, delta=-0.5)
        assert o2.strike == result.strike
Exemplo n.º 23
0
    def test_open_short_call(self):
        path = Path('tests/test_data/normalized/TSLA')
        training = pd.read_csv(path / 'training.csv',
                               parse_dates=['date'],
                               date_parser=from_small_date)
        portfolio = Portfolio(cash=0, securities={TSLA: 100})

        sim = Simulator(TSLA, portfolio, path, training)
        sim._sell(
            datetime(2020, 7, 20),
            0.293070701634208,  # normalized close for 7/20
            0.4617712204180135,  # should target the 2000 strike
            0.3087888191319731  # should target 8/21 expiration
        )

        call = Option('call', TSLA, 2000, datetime(2020, 8, 21))
        self.assertEqual(-1, portfolio.securities[call])
        self.assertEqual(100, portfolio.securities[TSLA])
        self.assertEqual(100, portfolio.collateral[TSLA])
        self.assertEqual(10875, portfolio.cash)
Exemplo n.º 24
0
 def parse_chain(self, date, security, path):
     chain = OptionChain(security, date)
     df = pd.read_csv(path,
                      parse_dates=['expiration'],
                      date_parser=from_small_date)
     for index, contract in df.iterrows():
         expiration = contract['expiration']
         direction = contract['direction']
         strike = contract['strike']
         option = Option(direction, security, strike, expiration)
         option.price = contract['price']
         option.delta = contract['delta']
         option.theta = contract['theta']
         option.vega = contract['vega']
         chain.add_option(option)
     return chain
Exemplo n.º 25
0
 def test_option_expired(self):
     security = Security('TSLA')
     call = Option('call', security, 420, datetime(2020, 12, 4))
     self.assertTrue(call.expired(datetime(2020, 12, 4)))
     self.assertTrue(call.expired(datetime(2020, 12, 5)))
Exemplo n.º 26
0
    def test_iv(self):
        security = Security('TSLA')
        security.add_quote(Quote(420, datetime.now()))
        o1 = Option('call', security, 700, datetime(2020, 4, 20))
        o3 = Option('call', security, 500, datetime(2020, 4, 20))
        o2 = Option('put', security, 400, datetime(2020, 4, 20))
        o1.iv = 5
        o1.price = 2
        o2.iv = 2
        o2.price = 4
        o3.iv = 0.5
        o3.price = 10

        chain = OptionChain(security, datetime.now())
        chain.add_option(o1)
        chain.add_option(o2)
        chain.add_option(o3)

        expected = (5 * 2 + 2 * 4 + 0.5 * 10) / (2 + 4 + 10)
        result = chain.iv(datetime(2020, 4, 20))
        self.assertEqual(expected, result)
Exemplo n.º 27
0
    def test_contracts(self):
        call = Option('call', TSLA, 500, datetime(2020, 12, 28))
        p = Portfolio(0, {call: 1})

        self.assertEqual(1, p.contracts()[call])