-
Notifications
You must be signed in to change notification settings - Fork 37
/
ib_portfolio_monitor.py
361 lines (289 loc) · 11 KB
/
ib_portfolio_monitor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import argparse
import math
from abc import ABC
from abc import abstractmethod
from datetime import datetime
from typing import Dict
from typing import List
from ib_async import Contract
from ib_async import Future
from ib_async import FuturesOption
from ib_async import Index
from ib_async import Option
from ib_async import Position
from ib_async import Stock
from ib_async import Ticker
from common.ib import get_next_futures_expiry
from common.ib import setup_ib
ib = setup_ib()
ib.reqMarketDataType(2)
def get_open_positions() -> List[Position]:
return ib.positions()
def get_market_price(contract: Contract) -> Ticker:
[ticker] = ib.reqTickers(*[contract])
return ticker
def filter_open_positions_for_options_trades(
positions: List[Position],
) -> List[Position]:
return [
pos for pos in positions if isinstance(pos.contract, (Option, FuturesOption))
]
def group_by_expiry_dates(positions: List[Position]) -> Dict[str, List[Position]]:
grouped = {}
for pos in positions:
if isinstance(pos.contract, (Option, FuturesOption)):
expiry = pos.contract.lastTradeDateOrContractMonth
if expiry not in grouped:
grouped[expiry] = []
grouped[expiry].append(pos)
return grouped
class OptionStrategy(ABC):
@abstractmethod
def is_match(self, trade_legs: List[Position]) -> bool:
pass
@abstractmethod
def adjustment_required(
self, days_to_expiry: int, latest_prices: Dict[str, float]
) -> bool:
pass
@abstractmethod
def simulate_adjustments(
self,
trades: List[Position],
days_to_expiry: int,
latest_prices: Dict[str, float],
):
pass
class ShortStraddle(OptionStrategy):
def is_match(self, trade_legs: List[Position]) -> bool:
return (
len(trade_legs) == 2
and trade_legs[0].contract.right != trade_legs[1].contract.right
and trade_legs[0].position < 0
and trade_legs[1].position < 0
and trade_legs[0].contract.strike == trade_legs[1].contract.strike
)
def adjustment_required(
self, days_to_expiry: int, latest_prices: Dict[str, float]
) -> bool:
return False
def simulate_adjustments(
self,
trades: List[Position],
days_to_expiry: int,
latest_prices: Dict[str, float],
):
pass
class ShortStrangle(OptionStrategy):
def is_match(self, trade_legs: List[Position]) -> bool:
return (
len(trade_legs) == 2
and trade_legs[0].contract.right != trade_legs[1].contract.right
and trade_legs[0].position < 0
and trade_legs[1].position < 0
and trade_legs[0].contract.strike != trade_legs[1].contract.strike
)
def adjustment_required(
self, days_to_expiry: int, latest_prices: Dict[str, float]
) -> bool:
return False
def simulate_adjustments(
self,
trades: List[Position],
days_to_expiry: int,
latest_prices: Dict[str, float],
):
pass
class IronCondor(OptionStrategy):
def is_match(self, trade_legs: List[Position]) -> bool:
if len(trade_legs) < 4:
return False
calls = sorted(
[leg for leg in trade_legs if leg.contract.right == "C"],
key=lambda x: x.contract.strike,
)
puts = sorted(
[leg for leg in trade_legs if leg.contract.right == "P"],
key=lambda x: x.contract.strike,
)
if len(calls) < 2 or len(puts) < 2:
return False
return (
calls[0].position > 0 > calls[-1].position
and puts[0].position > 0 > puts[-1].position
and puts[0].contract.strike
< puts[-1].contract.strike
< calls[0].contract.strike
< calls[-1].contract.strike
)
def adjustment_required(
self, days_to_expiry: int, latest_prices: Dict[str, float]
) -> bool:
return False
def simulate_adjustments(
self,
trades: List[Position],
days_to_expiry: int,
latest_prices: Dict[str, float],
):
pass
class IronButterflyStraddleAdjustment:
pass
class IronButterfly(OptionStrategy):
def __init__(self):
self.adjustments = [IronButterflyStraddleAdjustment()]
def is_match(self, trade_legs: List[Position]) -> bool:
if len(trade_legs) != 4:
return False
short_legs = [leg for leg in trade_legs if leg.position < 0]
long_legs = [leg for leg in trade_legs if leg.position > 0]
if len(short_legs) != 2 or len(long_legs) != 2:
return False
short_strike = short_legs[0].contract.strike
if not all(leg.contract.strike == short_strike for leg in short_legs):
return False
long_put = next((leg for leg in long_legs if leg.contract.right == "P"), None)
long_call = next((leg for leg in long_legs if leg.contract.right == "C"), None)
return (
long_put
and long_call
and long_put.contract.strike < short_strike < long_call.contract.strike
)
def adjustment_required(
self, days_to_expiry: int, latest_prices: Dict[str, float]
) -> bool:
return True
def simulate_adjustments(
self,
trades: List[Position],
days_to_expiry: int,
latest_prices: Dict[str, float],
):
pass
class UnknownStrategy(OptionStrategy):
def is_match(self, trade_legs: List[Position]) -> bool:
return True
def adjustment_required(
self, days_to_expiry: int, latest_prices: Dict[str, float]
) -> bool:
return False
def simulate_adjustments(
self,
trades: List[Position],
days_to_expiry: int,
latest_prices: Dict[str, float],
):
pass
class StrategyFactory:
def __init__(self):
self.strategies = [
ShortStraddle(),
ShortStrangle(),
IronCondor(),
IronButterfly(),
UnknownStrategy(),
]
def get_strategy(self, trade_legs: List[Position]) -> OptionStrategy:
for strategy in self.strategies:
if strategy.is_match(trade_legs):
return strategy
return UnknownStrategy()
def determine_strategy_type(trade_legs: List[Position]) -> OptionStrategy:
if not trade_legs:
return UnknownStrategy()
factory = StrategyFactory()
return factory.get_strategy(trade_legs)
def generate_pl_payoff_diagrams(position: Position) -> str:
if isinstance(position.contract, (Option, FuturesOption)):
return f"P/L and Payoff diagram for {position.contract.symbol} {position.contract.right}{position.contract.strike}"
return f"P/L and Payoff diagram for {position.contract.symbol}"
def get_market_data(symbol: str, strike: float) -> Dict:
return {"symbol": symbol, "price": 150.0, "iv": 0.3}
def generate_report(positions: List[Position], adjustments: Dict) -> str:
report = "Trade Report:\n\n"
# for pos in positions:
# report += f"Account: {pos.account}\n"
# report += f"Symbol: {pos.contract.symbol}\n"
# report += f"Type: {type(pos.contract).__name__}\n"
# if isinstance(pos.contract, (Option, FuturesOption)):
# report += f"Strike: {pos.contract.strike}\n"
# report += f"Expiry: {pos.contract.lastTradeDateOrContractMonth}\n"
# report += f"Position: {pos.position}\n"
# report += f"Avg Cost: {pos.avgCost}\n"
# if pos.contract.localSymbol in adjustments:
# report += f"Proposed Adjustments: {', '.join(adjustments[pos.contract.localSymbol])}\n"
# report += "\n"
return report
def get_underlying_contract(contract_symbol, contract_last_trade_date) -> Contract:
if contract_symbol == "SPX":
return Index("SPX", exchange="CBOE")
elif contract_symbol == "XSP":
return Index("XSP", exchange="CBOE")
elif contract_symbol == "ES":
return Future(
"ES",
exchange="CME",
lastTradeDateOrContractMonth=get_next_futures_expiry(
contract_last_trade_date
),
)
else:
return Stock(contract_symbol, "SMART", "USD")
def get_latest_prices(positions: List[Position]) -> Dict[str, float]:
unique_underlyings = {}
for position in positions:
symbol = position.contract.symbol
storage_key = f"{symbol}_{position.contract.lastTradeDateOrContractMonth}"
if storage_key not in unique_underlyings:
print(f"Getting underlying for {position.contract}")
underlying = get_underlying_contract(
symbol, position.contract.lastTradeDateOrContractMonth
)
unique_underlyings[storage_key] = underlying
underlyings_list = list(unique_underlyings.values())
batch_prices = get_latest_price(underlyings_list)
prices = {}
for storage_key, underlying in unique_underlyings.items():
index = underlyings_list.index(underlying)
price = batch_prices[index]
prices[storage_key] = price
print(f"Fetched price for {storage_key}: {price}")
return prices
def get_latest_price(underlyings) -> List[float]:
tickers = ib.reqTickers(*underlyings)
prices = []
for ticker in tickers:
ticker_price = ticker.marketPrice()
price = ticker.close if math.isnan(ticker_price) else ticker_price
prices.append(price)
return prices
def main(args):
open_positions = ib.positions()
options_trades = filter_open_positions_for_options_trades(open_positions)
latest_prices = get_latest_prices(options_trades)
print(f"Latest prices: {latest_prices}")
grouped_trades = group_by_expiry_dates(options_trades)
adjustments = {}
for expiry, trades in grouped_trades.items():
print(f"Looking at {trades} expiring on {expiry}")
options_strategy = determine_strategy_type(trades)
options_strategy_name = options_strategy.__class__.__name__
print(f"Options Strategy used: {options_strategy_name}")
days_to_expiry = (datetime.strptime(expiry, "%Y%m%d") - datetime.now()).days
if options_strategy.adjustment_required(days_to_expiry, latest_prices):
print(f"⚠️ Adjustment required for {options_strategy_name}")
options_strategy.simulate_adjustments(trades, days_to_expiry, latest_prices)
else:
print(f"✅ No Adjustment required for {options_strategy_name}")
# for trade in trades:
# pl_payoff = generate_pl_payoff_diagrams(trade)
# print(f"Generated: {pl_payoff}")
#
# market_data = get_market_data(trade.contract.symbol, trade.contract.strike)
# print(f"Market data for {trade.contract.symbol}: {market_data}")
report = generate_report(open_positions, adjustments)
print(report)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Process options trades")
args = parser.parse_args()
main(args)