Skip to content

Commit

Permalink
Fix handling for net short edge case
Browse files Browse the repository at this point in the history
  • Loading branch information
brndnmtthws committed Feb 1, 2024
1 parent f51dc51 commit a3755a5
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 12 deletions.
30 changes: 30 additions & 0 deletions thetagang/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,36 @@ def test_calculate_net_short_positions() -> None:
"C",
)

assert 5 == calculate_net_short_positions(
[
con(exp3dte, 60, "P", -10),
con(exp30dte, 69, "P", -1),
con(exp90dte, 69, "P", 1),
con(exp90dte, 68, "P", 5),
],
"P",
)

assert 10 == calculate_net_short_positions(
[
con(exp3dte, 70, "P", -10),
con(exp30dte, 69, "P", -1),
con(exp90dte, 69, "P", 1),
con(exp90dte, 68, "P", 5),
],
"P",
)

assert 0 == calculate_net_short_positions(
[
con(exp3dte, 60, "P", -10),
con(exp30dte, 69, "P", -1),
con(exp90dte, 69, "P", 1),
con(exp90dte, 68, "P", 50),
],
"P",
)


def test_weighted_avg_strike() -> None:
today = date.today()
Expand Down
24 changes: 12 additions & 12 deletions thetagang/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,25 +115,25 @@ def calculate_net_short_positions(positions: List[PortfolioItem], right: str) ->
longs = sorted(longs, key=itemgetter(0, 1), reverse=right.upper().startswith("P"))

def calc_net(short_dte: int, short_strike: float, short_position: float) -> float:
net = short_position
for i in range(len(longs)):
if short_position > -1:
break
(long_dte, long_strike, long_position) = longs[i]
if long_position < 1:
# ignore empty long positions
continue
if long_dte >= short_dte:
if (right.upper().startswith("P") and long_strike >= short_strike) or (
right.upper().startswith("C") and long_strike <= short_strike
):
net = short_position + long_position
if net > 0:
short_position = 0
long_position = net
elif net < 0:
long_position = 0
short_position = net
else:
long_position = 0
short_position = 0
if short_position + long_position > 0:
short_position = 0
long_position = short_position + long_position
else:
short_position += long_position
long_position = 0
longs[i] = (long_dte, long_strike, long_position)
return min([0.0, net])
return min([0.0, short_position])

nets = [calc_net(*short) for short in shorts]

Expand Down

0 comments on commit a3755a5

Please sign in to comment.