PortfolioManager API Reference
tradingbot.utils.portfolio_manager.PortfolioManager(bot_name: str, data_service: DataService, bot_repository: type[BotRepository], execution_config: ExecutionConfig | None = None)
Manages portfolio operations including buying, selling, and rebalancing.
Initialize portfolio manager.
No ORM row is ever kept on the instance. Writers lock the bot's row inside their own transaction and let it go with the session; readers take a plain dict (_portfolio). A row held across sessions is expired at commit and detached at close, and reading it raises DetachedInstanceError at whichever call happens to come next.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bot_name
|
str
|
Name of the bot whose |
required |
data_service
|
DataService
|
DataService instance for fetching prices |
required |
bot_repository
|
type[BotRepository]
|
BotRepository class (used via its staticmethods, never instantiated) |
required |
execution_config
|
ExecutionConfig | None
|
Costs and no-trade band. Injected rather than read
from the module singleton so tests can vary it: this module did
|
None
|
Source code in tradingbot/utils/portfolio_manager.py
assign_before_dividends(physical: bool, today=None) -> list[str]
Early assignment of short ITM calls whose extrinsic value is below the next dividend, on the session before the ex-date (or the ex-date itself, if the bot did not run the day before). Returns the keys assigned.
Source code in tradingbot/utils/portfolio_manager.py
buy(symbol: str, quantity_usd: float = -1, cached_data: pd.DataFrame | None = None, session: Session | None = None, option: bool | str | None = None, target_dte: int = 30, target_delta: float | None = None) -> None
Buy a quantity of the specified symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Trading symbol to buy — for options, the UNDERLYING |
required |
quantity_usd
|
float
|
Amount in USD to spend (-1 means use all available cash) |
-1
|
cached_data
|
DataFrame | None
|
Optional cached DataFrame for price lookup |
None
|
session
|
Session | None
|
Optional existing database session |
None
|
option
|
bool | str | None
|
None/False buys the symbol itself. True / "call" / "put" buys a contract on it instead, chosen by options.select_contract (first expiry >= target_dte days out, strike nearest spot). |
None
|
target_dte
|
int
|
Minimum days to expiry for the selected contract. |
30
|
target_delta
|
float | None
|
Pick the strike nearest this delta (e.g. 0.70) instead of the one nearest spot. |
None
|
Cash reserved as margin for short option legs (see options.margin_requirement) is never spendable here. That is 0 for any bot without short options.
Source code in tradingbot/utils/portfolio_manager.py
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 | |
close_options(underlying: str, session: Session | None = None, include_stock: bool = False) -> float
Flatten every option leg on underlying, long and short, in one
transaction. include_stock also flattens the shares held beside them
(the hedge of a straddle, the stock of a collar).
Source code in tradingbot/utils/portfolio_manager.py
delta_hedge(underlying: str, band_usd: float, ww: tuple[float, float] | None = None) -> float
Trade whole shares so the net delta of the options plus shares on
underlying returns to about zero, once its dollar value exceeds
band_usd. Returns the shares traded (signed). Gamma scalping is this,
run every day on a long straddle: it sells rallies and buys dips.
ww=(cost_frac, risk_aversion) uses the Whalley-Wilmott band instead (option_rules.hedge_trade): rehedge only outside it, and only to its edge.
Source code in tradingbot/utils/portfolio_manager.py
open_structure(pick: options.StructurePick, max_risk_usd: float) -> int
Open as many units of pick as max_risk_usd of worst-case loss allows.
One unit is one contract per option leg, 100 shares per stock leg (signs from the pick). Max loss per unit is taken from the prices it would fill at (ask on the long legs, bid on the short), so for a credit spread it is width - credit, for a collar stock - put strike + net debit. Refuses when the chain was not live: off-hours last prices on different legs are from different moments, and a "credit" built from them is fiction.
Returns:
| Type | Description |
|---|---|
int
|
Units opened (0 when refused or unaffordable). |
Source code in tradingbot/utils/portfolio_manager.py
option_book(underlying: str) -> options.OptionBook
Positions, marks, entry value, P&L and net greeks of the options on underlying.
Source code in tradingbot/utils/portfolio_manager.py
rebalance_portfolio(target_portfolio: dict[str, float], only_over_50_usd: bool = False) -> None
Rebalance portfolio to match target weights in a single transaction with row locking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_portfolio
|
dict[str, float]
|
Dictionary mapping symbols to target weights (e.g., {"VWCE": 0.8, "GLD": 0.1, "USD": 0.1}) Weights must sum to 1.0 (100%) |
required |
only_over_50_usd
|
bool
|
If True, filter out assets with target value <= $50 |
False
|
Source code in tradingbot/utils/portfolio_manager.py
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 | |
roll_and_settle_options(roll_dte: int | None, target_dte: int, target_delta: float | None = None, settlement: str = 'cash') -> None
Keep option positions alive without the bot having to think about expiry.
- Contracts already past expiry are settled off the underlying's close on the expiry date, long and short alike. settlement="cash" pays the intrinsic value. settlement="physical" does what a broker does: an ITM contract becomes shares at the strike (a short put is assigned 100 shares per contract, a short call delivers them), except any part that would leave the book short stock, which is cash-settled instead.
- Long contracts with <= roll_dte days left are sold and the proceeds rebought in a fresh contract on the same underlying and side (at target_delta if given), so "I hold an AAPL call" stays true across expiries. roll_dte=None disables rolling.
- An underlying with any SHORT leg is never rolled: rolling one wing of a spread alone would leave the short side uncovered. Strategies that sell options manage their own exits.
- A short ITM call is assigned EARLY on the last session before its underlying goes ex-dividend when its extrinsic value is below the dividend: that is when a rational holder exercises to collect it (assign_before_dividends). Physical bots deliver shares, cash bots settle at intrinsic. Bots avoid it by closing the call first (option_rules.ex_dividend_close_reason).
A no-op for a bot holding no options.
Source code in tradingbot/utils/portfolio_manager.py
sell(symbol: str, quantity_usd: float = -1, cached_data: pd.DataFrame | None = None, session: Session | None = None, option: bool | str | None = None) -> float
Sell a quantity of the specified symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Trading symbol to sell — for options, the UNDERLYING |
required |
quantity_usd
|
float
|
Amount in USD to sell (-1 means sell all holdings) |
-1
|
cached_data
|
DataFrame | None
|
Optional cached DataFrame for price lookup |
None
|
session
|
Session | None
|
Optional existing database session |
None
|
option
|
bool | str | None
|
None/False sells the symbol itself. True sells every option held on it; "call" / "put" only that side. Earliest expiry first. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Net cash credited (0.0 if nothing was sold). |
Source code in tradingbot/utils/portfolio_manager.py
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 362 363 364 365 366 | |
total_value() -> float
Cash plus every holding (short option legs negative) at the latest price.
Source code in tradingbot/utils/portfolio_manager.py
trade_option_legs(legs: list[tuple[str, float]], session: Session | None = None) -> float
Change several option positions in ONE locked transaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
legs
|
list[tuple[str, float]]
|
(symbol, signed share-equivalent change). For an OCC contract +200 buys two contracts (to open or to close a short), -200 sells two (to close a long or to open a short); whole contracts only. The underlying's own symbol trades shares — allowed only when the trade or the book holds options on it (buy-writes, collars, delta hedges), and the only way to go short stock. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Net cash flow: positive for a credit, negative for a debit. |
This is the only path that can make a holding negative. Each option leg fills at the ask when buying and the bid when selling (last price +/- option slippage without a market); stock legs use the stock cost model. If the trade opens or grows any position, it is refused as a whole — nothing is written — when the cash left would not cover options.margin_requirement of the resulting book. That also refuses anything with unbounded risk, such as a naked short call. Pure reductions always go through, so a position can always be closed.
Source code in tradingbot/utils/portfolio_manager.py
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 | |