MCPcopy Index your code
hub / github.com/brndnmtthws/thetagang

github.com/brndnmtthws/thetagang @v2.0.2

Chat with this repo
repository ↗ · DeepWiki ↗ · release v2.0.2 ↗ · + Follow
928 symbols 3,394 edges 60 files 96 documented · 10%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Docker publish Python Publish Docker Pulls PyPI download month

💬 Join the Matrix chat, we can get money together.

Θ ThetaGang Θ

Beat the capitalists at their own game with ThetaGang 📈

Decay my sweet babies

ThetaGang is an IBKR trading bot that started as a basic implementation of "The Wheel" strategy and has grown into a broader, configurable portfolio automation tool. ThetaGang still supports a modified version of The Wheel, and now also includes features like direct share rebalancing, cash management, VIX call hedging, regime-aware rebalancing, and exchange-hours gating.

Risk Disclaimer

⚠️ WARNING: Options trading involves substantial risk and is not suitable for all investors. Selling options can result in significant losses, potentially exceeding your initial investment. Selling naked puts has theoretically unlimited downside risk if the underlying asset goes to zero. This is not a "free money" strategy—you are being compensated for taking on real financial risk.

Before using ThetaGang: - Understand that you can lose money, especially in trending or volatile markets - Ensure you have sufficient capital to handle worst-case scenarios - Be prepared to own the underlying securities at potentially unfavorable prices - Consider paper trading first to understand the mechanics and risks - Consult with a financial advisor if you're unsure about the risks

How it works

The strategy, as implemented here, is intended to be used to augment a typical index-fund based portfolio with specific asset allocations. The default configuration includes a diversified portfolio with SPY (40%), QQQ (30%), TLT (20%), and smaller positions in individual stocks. This strategy reduces risk, but may also limit gains from big market swings. By reducing risk, one can increase leverage.

ThetaGang is quite configurable, and you can adjust the parameters to suit your preferences and needs, but the default configuration is designed to be a good starting point. ThetaGang makes some assumptions about how to run this strategy, but you can tweak it to your liking by modifying the thetagang.toml file.

The main difference between ThetaGang and simply buying and holding index funds is that this script will attempt to harvest volatility by selling options, rather than buying shares directly. This works because implied volatility is typically higher than realized volatility on average. Instead of buying shares, you write puts. This has pros and cons, which are outside the scope of this README.

ThetaGang can also be used in combination with other strategies such as PMCCs, Zebra, stock replacement, and so forth. For these strategies, however, ThetaGang will not manage long positions for you. You will need to manage these positions yourself. ThetaGang will, however, continue to execute the short legs of these strategies as long as you have the buying power available and set the appropriate configuration (in particular, by setting write_when.calculate_net_contracts = true).

Running multiple strategies safely

If you want to run materially different strategies, it is strongly recommended to use separate IBKR accounts (for example, separate linked sub-accounts) and fund each one independently.

Mixing multiple strategy styles in one account can produce confusing or harmful interactions because ThetaGang decisions are account-level. Buying power usage, position targeting, rebalancing logic, option rolls, cash management, and hedge logic all see the same combined portfolio and can interfere with each other in ways that are hard to reason about.

In practice, one strategy per account is usually the cleanest setup: - Cleaner risk boundaries and capital budgets - Cleaner performance attribution - Fewer unexpected cross-strategy side effects - Easier debugging when behavior is not what you expected

Over time, additional features were added to support different portfolio workflows and risk controls. You can enable or disable them independently via config:

  • Direct share rebalancing (buy-only and sell-only modes)
  • Cash management via a cash-equivalent fund
  • VIX call hedging
  • Regime-aware rebalancing gates
  • Exchange-hours enforcement

ThetaGang will try to acquire your desired allocation of each stock or ETF according to the weights you specify in the config. To acquire the positions, the script will write puts when conditions are met (config parameters, adequate buying power, acceptable contracts are available, enough shares needed, etc).

ThetaGang will continue to roll any open option positions indefinitely, with the only exception being ITM puts (although this is configurable). Once puts are in the money, they will be ignored until they expire and are exercised (after which you will own the underlying). When rolling puts, the strike of the new contracts are capped at the old strike plus the premium received (to prevent your account from blowing due to over-ratcheting up the buying power usage).

If puts are exercised due to being ITM at expiration, you will own the stock, and ThetaGang switches from writing puts to writing calls at a strike at least as high as the average cost of the stock held. To avoid missing out on upward moves, you can limit the number of calls that are written with write_when.calls.cap_factor, such as setting this to 0.5 to limit the number of calls to 50% of the shares held.

Please note: this strategy is based on the assumption that implied volatility is, on average, always higher than realized volatility. In cases where this is not true, this strategy will cause you to lose money.

In the case of deep ITM calls, the bot will prefer to roll the calls to next strike or expiration rather than allowing the underlying to get called away. If you don't have adequate buying power available in your account, it's possible that the options may get exercised instead of rolling forward and the process starts back at the beginning. Please keep in mind this may have tax implications, but that is outside the scope of this README.

In normal usage, you would run the script as a cronjob on a daily, weekly, or monthly basis according to your preferences. Running more frequently than daily is not recommended, but the choice is yours. Some features (like regime-aware rebalancing) assume a daily cadence.

Paper account sample output

VIX call hedging

ThetaGang can optionally hedge your account by purchasing VIX calls for the next month based on specified parameters. The strategy is based on the Cboe VIX Tail Hedge Index, which you can read about on the internet. You can enable this feature in thetagang.toml with:

[vix_call_hedge]
enabled = true

Default values are provided, based on the VXTH index, but you may configure them to your taste. Key parameters include:

[vix_call_hedge]
enabled = true
allocation = 0.01  # 1% of buying power
close_hedges_when_vix_exceeds = 50  # Auto-close at high VIX
ignore_dte = 5  # Don't hedge if expiry within 5 days

See thetagang.toml for all available options.

Buying VIX calls is not free, and it will create some drag on your portfolio, but in times of extreme volatility–such as the COVID-related 2020 market panic–VIX calls can provide outsized returns.

Cash management

At the time of writing, interest rates have reached yields that make bonds look attractive. To squeeze a little more juice, thetagang can do some simple cash management by purchasing a fund when you have extra cash. Although you do earn a yield on your cash balance, it's not the juiciest yield you can get, so a little optimization might help you earn 1 or 2 extra pennies to take the edge off your rent payments.

You can enable cash management with:

[cash_management]
enabled = true
fund = "SGOV"  # Default short-term treasury ETF
buy_threshold = 0.01  # Buy when cash > 1% of buying power
sell_threshold = 0.005  # Sell when cash < 0.5%

[cash_management.orders]
algo.strategy = "Vwap"  # Use VWAP for cash fund orders

This feature uses VWAP (Volume Weighted Average Price) orders by default to minimize market impact when moving in and out of cash positions. Refer to thetagang.toml for all the options.

Advanced Features

ThetaGang includes several advanced features that provide fine-grained control over your trading strategy:

Buy-Only Rebalancing

For symbols where options premiums are insufficient or unavailable, you can enable direct stock purchases for portfolio rebalancing:

[symbols.AAPL]
buy_only_rebalancing = true
buy_only_min_threshold_shares = 10  # Minimum shares to buy
buy_only_min_threshold_amount = 1000  # Minimum dollar amount to buy

This feature is useful for maintaining target allocations in stocks with limited options liquidity or when you want to dollar-cost average into positions.

Regime-Aware Rebalancing

Regime-aware rebalancing lets you gate share rebalances on a simple regime filter before acting. It builds a proxy series from the configured symbols’ daily closes, then checks for “choppy/mean-reverting” conditions using choppiness and efficiency thresholds. If the regime passes, and allocations drift beyond the soft relative band around target weights (or cash flow moves all positions in the same direction), it queues share trades to move back toward targets. A hard relative band acts as a safety rail and triggers even when the regime filter fails, optionally rebalancing only partway back to target. A cooldown prevents frequent soft-band rebalances and is based on recent executions tagged with tg:regime-rebalance. When using this feature, run the script once per day.

[regime_rebalance]
enabled = true
symbols = ["QQQ", "BTAL"]
lookback_days = 40
soft_band = 0.25  # +/-25% relative drift from target weight
hard_band = 0.50  # +/-50% relative drift from target weight
hard_band_rebalance_fraction = 1.0  # 1.0 = full to target, 0.5 = halfway
cooldown_days = 5
choppiness_min = 3.0
efficiency_max = 0.30
order_history_lookback_days = 30
shares_only = true  # disable option writes/rolls while rebalancing

Exchange Hours Management

Control when ThetaGang operates relative to market hours:

[exchange_hours]
exchange = "XNYS"  # NYSE by default
action_when_closed = "wait"  # Options: "wait", "exit", "continue"
delay_after_open = 1800  # Wait 30 minutes after market open
delay_before_close = 1800  # Stop 30 minutes before market close
max_wait_until_open = 3600  # Max wait time if market is closed

Strike Price Limits

Set boundaries for option strikes to prevent writing options at unfavorable prices:

[symbols.SPY.puts]
strike_limit = 400  # Don't write puts above $400

[symbols.SPY.calls]
strike_limit = 450  # Don't write calls below $450

Write Threshold Sigma

Use standard deviation-based thresholds instead of fixed percentages:

[constants]
write_threshold_sigma = 1.0  # Write when 1 standard deviation from current price

[symbols.QQQ.puts]
write_threshold_sigma = 1.5  # More conservative for this symbol

When specified, sigma thresholds override regular write_threshold values.

Advanced Rolling Features

Maintain High Water Mark

Prevent rolling calls to lower strikes:

[roll_when.calls]
maintain_high_water_mark = true

Close If Unable to Roll

Automatically close positions when suitable roll contracts aren't available:

[roll_when]
close_if_unable_to_roll = true

Order Management

Price Adjustments

Automatically adjust limit orders after initial delay:

[symbols.SPY]
adjust_price_after_delay = true  # Adjusts to midpoint after delay

Algorithm Configuration

Customize order execution algorithms:

[orders.algo]
strategy = "Adaptive"
params.priority = "Patient"  # Options: "Urgent", "Normal", "Patient"

Position Management

Calculate Net Contracts

Enable for spread strategies (PMCCs, calendars):

[write_when]
calculate_net_contracts = true

Excess Only for Calls

Write calls only on shares exceeding target allocation:

[write_when.calls]
excess_only = true

No Trading Flag

Temporarily disable trading for specific symbols:

[symbols.TSLA]
no_trading = true  # Monitor only, no trades

API Configuration

Fine-tune IBKR API behavior:

[ib_async]
api_response_wait_time = 60  # Seconds to wait for API responses
logfile = "ib_async.log"  # Enable API logging for debugging

Target Limits

Set absolute caps on new contracts:

[target]
maximum_new_contracts = 10  # Absolute limit per run
maximum_new_contracts_percent = 0.5  # Or limit by percentage

Project status

This project is, in its current state, considered to be complete. I'm open to contributions, but I am unlikely to accept PRs or feature requests that involve significant changes to the underlying algorithm.

If you find something that you think is a bug, or some other issue, please [create a new issue](https://github.com/brndnmtthws/thetagang/issu

Core symbols most depended-on inside this repo

Shape

Method 431
Function 368
Class 125
Route 4

Languages

Python100%

Modules by API surface

tests/test_regime_rebalance.py80 symbols
thetagang/config.py72 symbols
thetagang/portfolio_manager.py70 symbols
thetagang/config_models.py54 symbols
thetagang/strategies/options_engine.py44 symbols
thetagang/ibkr.py43 symbols
tests/test_portfolio_manager.py35 symbols
tests/test_config_migration.py34 symbols
thetagang/db.py32 symbols
tests/test_ibkr.py32 symbols
thetagang/strategies/regime_engine.py30 symbols
tests/test_config_new.py27 symbols

Datastores touched

dbDatabase · 1 repos

For agents

$ claude mcp add thetagang \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page