-
Notifications
You must be signed in to change notification settings - Fork 0
/
stock_options.py
executable file
·177 lines (161 loc) · 6.54 KB
/
stock_options.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
#!/usr/bin/env python3
"""Methods for stock options."""
import io
import subprocess
import pandas as pd
import common
import etfs
def options_df():
"""Get call and put dataframe."""
cmd = (
f"{common.LEDGER_BIN} -f {common.LEDGER_DAT} --limit 'commodity=~/ (CALL|PUT)/' bal "
+ '--no-total --flat --balance-format "%(partial_account)\n%(strip(T))\n"'
)
entries = []
for line in io.StringIO(subprocess.check_output(cmd, shell=True, text=True)):
if line[0].isalpha():
account = line.strip()
continue
count = line.split(maxsplit=1)[0]
call_name = line.split(maxsplit=1)[1].strip().strip('"')
ticker = call_name.split()[0]
option_type = call_name.split()[-1]
strike = call_name.split()[-2]
expiration = call_name.split()[-3]
entries.append(
{
"name": call_name,
"type": option_type,
"ticker": ticker,
"count": int(count),
"strike": int(strike),
"expiration": pd.to_datetime(expiration),
"account": account,
}
)
calls_df = pd.DataFrame(entries)
etfs_df = pd.read_csv(
etfs.CSV_OUTPUT_PATH, index_col=0, usecols=["ticker", "current_price"]
).fillna(0)
joined_df = pd.merge(calls_df, etfs_df, on="ticker").set_index(
["account", "name", "expiration"]
)
joined_df.loc[joined_df["type"] == "CALL", "in_the_money"] = (
joined_df["strike"] < joined_df["current_price"]
)
joined_df.loc[joined_df["type"] == "PUT", "in_the_money"] = (
joined_df["strike"] > joined_df["current_price"]
)
joined_df["exercise_value"] = joined_df["strike"] * joined_df["count"] * 100
joined_df.loc[
(joined_df["type"] == "CALL") & (joined_df["count"] < 0), "exercise_value"
] = abs(joined_df["strike"] * joined_df["count"] * 100)
joined_df.loc[
(joined_df["type"] == "PUT") & (joined_df["count"] < 0),
"exercise_value",
] = abs(joined_df["strike"] * joined_df["count"] * 100) * -1
joined_df["intrinsic_value"] = 0.0
joined_df.loc[
(joined_df["type"] == "CALL") & joined_df["in_the_money"],
"intrinsic_value",
] = abs(
(joined_df["current_price"] - joined_df["strike"]) * joined_df["count"] * 100
)
joined_df.loc[
(joined_df["type"] == "PUT") & joined_df["in_the_money"],
"intrinsic_value",
] = abs(
(joined_df["strike"] - joined_df["current_price"]) * joined_df["count"] * 100
)
joined_df["min_contract_price"] = 0.0
joined_df.loc[joined_df["in_the_money"], "min_contract_price"] = joined_df[
"intrinsic_value"
] / (joined_df["count"] * 100)
return joined_df.sort_values(["account", "expiration", "name"]).round(2)
def short_put_exposure(dataframe, broker):
"""Get exposure of short puts along with long puts."""
broker_puts = dataframe.xs(broker, level="account").loc[
lambda df: df["type"] == "PUT"
]
broker_short_puts = broker_puts[broker_puts["count"] < 0]
total = 0
for index, _ in broker_short_puts.iterrows():
ticker_date = " ".join(index[0].split()[0:2])
total += sum(broker_puts.filter(like=ticker_date, axis=0)["exercise_value"])
return total
def after_assignment(itm_df):
"""Output balances after assignment."""
etfs_df = pd.read_csv(etfs.CSV_OUTPUT_PATH, index_col=0).fillna(0)
etfs_df["shares_change"] = 0
etfs_df["liquidity_change"] = 0
for _, cols in itm_df.iterrows():
match cols["type"]:
case "CALL":
multiplier = 1
case "PUT":
multiplier = -1
etfs_df.loc[cols["ticker"], "shares"] += multiplier * cols["count"] * 100
etfs_df.loc[cols["ticker"], "shares_change"] += multiplier * cols["count"] * 100
etfs_df.loc[cols["ticker"], "liquidity_change"] += cols["exercise_value"]
etfs_df = etfs_df[etfs_df["shares_change"] != 0]
etfs_df["original_value"] = etfs_df["value"]
etfs_df["value"] = etfs_df["shares"] * etfs_df["current_price"]
etfs_df["value_change"] = etfs_df["value"] - etfs_df["original_value"]
# Figure out trade profits
for ticker, cols in etfs_df.iterrows():
try:
etf_options_trade_income = float(
subprocess.check_output(
f'{common.LEDGER_PREFIX} -J -n --limit "commodity=~/{ticker}.+(CALL|PUT)/" bal',
text=True,
shell=True,
).split()[1]
)
etfs_df.loc[ticker, "options_trade_income"] = -etf_options_trade_income
except IndexError:
pass
etfs_df["profit_or_loss"] = (
etfs_df["value_change"]
+ etfs_df["liquidity_change"]
+ etfs_df["options_trade_income"]
)
print(etfs_df.round(2))
etfs_value_change = etfs_df["value_change"].sum()
options_trade_income = etfs_df["options_trade_income"].sum()
liquidity_change = etfs_df["liquidity_change"].sum()
profit_or_loss = etfs_df["profit_or_loss"].sum()
total_no_homes = common.read_sql_table("history").iloc[-1]["total_no_homes"]
total_no_homes_new = total_no_homes + etfs_value_change + liquidity_change
print(f"ETFs value change: {etfs_value_change:.0f}")
print(f"Liquidity change: {liquidity_change}")
print(" Ending balance:")
print(
f" Schwab: {itm_df.xs('Charles Schwab Brokerage')['exercise_value'].sum()}"
)
print(f" IBKR: {itm_df.xs('Interactive Brokers')['exercise_value'].sum()}")
print(f"Options trade income: {options_trade_income:.0f}")
print(f"Profit/loss compared to sale at current price: {profit_or_loss:.0f}")
print(
f"total_no_homes: {total_no_homes_new:.0f} (original: {total_no_homes:.0f}, "
f"difference: {total_no_homes_new - total_no_homes:.0f})\n"
)
def main():
"""Main."""
options = options_df()
print("Out of the money")
print(
options[options["in_the_money"] == False].drop( # noqa: E712
columns=["intrinsic_value", "min_contract_price"]
)
)
print("\nIn the money")
print(options[options["in_the_money"]], "\n")
print("Balances after in the money options assigned")
after_assignment(options[options["in_the_money"]])
for broker in ["Charles Schwab Brokerage", "Interactive Brokers"]:
print(f"{broker}")
print(f" Short put exposure: {short_put_exposure(options, broker)}")
print(options.xs(broker, level="account"))
print("\n")
if __name__ == "__main__":
main()