MCPInstall

rebalancing

Maintain portfolio allocations over time using calendar-based, threshold-based, and tax-efficient rebalancing strategies. Use when the user asks about when to rebalance, rebalancing bands, transaction cost trade-offs, tax-efficient rebalancing, or the rebalancing premium. Also trigger when users mention 'my portfolio drifted', 'how often should I rebalance', 'rebalancing across taxable and IRA accounts', 'volatility harvesting', 'buy low sell high automatically', or ask whether to use cash flows to rebalance.

Installs
740
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/joellewis/finance_skills --skill rebalancing
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads rebalancing automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Rebalancing

Core Concepts

Calendar Rebalancing

Rebalance at fixed time intervals regardless of drift magnitude:

  • Monthly: Tightest tracking to targets; highest transaction costs
  • Quarterly: Common institutional frequency; good balance of tracking and costs
  • Annually: Lowest cost; may allow significant drift between dates

Calendar rebalancing is simple to implement and schedule but may miss large dislocations between dates or trigger unnecessary trades when drift is minimal.

Threshold (Band) Rebalancing

Rebalance when any asset weight drifts beyond a defined tolerance band around its target:

  • Monitor weights continuously (or at regular intervals)
  • Trigger rebalancing when |w_actual - w_target| > tolerance
  • Typical bands: +/- 3% to +/- 5% (absolute) or +/- 20% to +/- 25% (relative)

Threshold rebalancing is more responsive to market dislocations and avoids unnecessary trades when markets are calm. However, it requires more frequent monitoring.

Optimal Band Width (Leland Model)

Leland (2000) derived the optimal no-trade band width as a function of transaction costs, risk aversion, and asset variance:

Band width proportional to (3 * transaction_cost / (2 * risk_aversion * variance))^(1/3)

Key intuition:

  • Higher transaction costs → wider bands (trade less)
  • Higher risk aversion → narrower bands (maintain target more tightly)
  • Higher variance → narrower bands (drift happens faster, risk of deviation is greater)

Rebalancing Premium

Systematic rebalancing generates a "volatility harvesting" or "rebalancing premium" through the buy-low/sell-high mechanism:

  • When an asset rises, its weight increases → rebalancing sells some (sell high)
  • When an asset falls, its weight decreases → rebalancing buys some (buy low)

This effect is sometimes called Shannon's Demon: in a two-asset portfolio with equal expected returns but independent volatility, the constantly rebalanced portfolio outperforms buy-and-hold. The rebalancing premium is larger when:

  • Asset volatilities are higher
  • Correlations are lower
  • Assets have similar expected returns (so mean-reversion dominates trends)

Note: The rebalancing premium is not a free lunch — it underperforms in trending markets where winners keep winning.

Transaction Costs

Costs incurred when rebalancing that reduce net returns:

  • Commissions: Per-trade or per-share fees (increasingly zero for retail)
  • Bid-ask spread: The cost of crossing the spread; wider for less liquid assets
  • Market impact: Price movement caused by the trade itself; significant for large positions in less liquid markets
  • Opportunity cost: Delay cost if rebalancing is deferred to avoid transaction costs

Total implementation cost = commissions + half-spread + market impact + opportunity cost

Tax-Efficient Rebalancing

Strategies to minimize tax impact when rebalancing in taxable accounts:

  1. Use cash flows: Direct new contributions to underweight assets and withdrawals from overweight assets
  2. Redirect dividends and interest: Reinvest income from overweight assets into underweight assets
  3. Rebalance with new contributions: The most tax-efficient method — no selling required
  4. Asset location: Hold tax-inefficient assets (bonds, REITs) in tax-deferred accounts; rebalance these freely
  5. Selective lot identification: When selling, choose tax lots with the highest cost basis (lowest gain) or lots held over one year (long-term capital gains rate)

Coordinating with Tax-Loss Harvesting (TLH)

Rebalancing and TLH should be planned together, not as separate trade lists:

  • Combine TLH sells with rebalance sells to reduce total trade count and transaction costs
  • An overweight position sitting at a loss is the ideal dual-purpose trade — the harvest and the rebalance are the same sell
  • Check open wash-sale windows before buying back or before rebalance buys in any account (including IRAs and spouse accounts)

Tax benefit = Realized loss * Marginal tax rate. For the 61-day wash-sale window, the $3,000 ordinary-income offset, replacement selection, and full TLH mechanics, see the tax-loss-harvesting skill.

Rebalancing Across Account Types

When an investor has multiple account types (taxable, IRA, 401k), optimize rebalancing by:

  • Tax-deferred accounts (IRA, 401k): Rebalance freely — no tax consequences
  • Taxable accounts: Minimize selling; use cash flows, TLH, and selective lot sales
  • Cross-account rebalancing: Consider the aggregate portfolio across all accounts and rebalance within the most tax-efficient account

Drift Tolerance Setting

Factors that determine optimal band width:

  • Tighter bands (e.g., +/- 2%): Better risk control, higher costs, appropriate for low-cost/institutional settings
  • Wider bands (e.g., +/- 10%): Lower costs, more drift risk, appropriate for taxable accounts with high tax impact
  • Asset-specific bands: More volatile assets may need wider absolute bands but tighter relative bands

Cash Flow Rebalancing

Use regular deposits or withdrawals to move toward target weights without explicit rebalancing trades:

  • Calculate current vs. target weights
  • Direct 100% of new contributions to the most underweight asset(s)
  • Process withdrawals from the most overweight asset(s)
  • This "natural rebalancing" is the most cost-effective and tax-efficient approach

Rebalancing Workflow

The concepts above describe the what and why of rebalancing. This section covers the operational how — the step-by-step process an advisor follows to execute a rebalance for a client household.

Step 1: Aggregate Household View Assemble the complete picture across all accounts (taxable brokerage, Traditional IRA, Roth IRA, 401(k), 529, trust). Calculate the household-level allocation by summing positions across all accounts, not just individual account allocations. Many drift problems are invisible at the account level but obvious at the household level.

Step 2: Asset Location Review Before proposing trades, document which account types hold which asset classes:

  • Tax-inefficient assets (bonds, REITs, high-turnover funds) should be in tax-deferred accounts
  • Tax-efficient assets (index equity ETFs, municipal bonds) should be in taxable accounts
  • Highest-growth assets should be in Roth accounts (permanent tax-free growth)

If asset location is suboptimal, the rebalance is an opportunity to improve it — but only if the tax cost of repositioning is justified by the long-term tax savings.

Step 3: Drift Analysis and Trade Generation For each asset class, calculate drift from target and compare against tolerance bands (from the IPS or firm default):

  • Generate a preliminary trade list: sell overweight positions, buy underweight positions
  • Prioritize trades by drift magnitude — address the largest deviations first
  • Check whether cash flows (pending contributions, withdrawals, dividends) can partially or fully close the drift without explicit trades

Step 4: Tax-Impact Estimation For each proposed sell trade in a taxable account, estimate the tax consequence:

  • Identify available tax lots and their holding periods (short-term vs long-term)
  • Calculate the estimated capital gain or loss for each lot using specific identification (HIFO preferred)
  • Sum the estimated tax liability across all proposed sells
  • Compare the tax cost against the risk-reduction benefit of rebalancing — defer trades where tax cost outweighs the tracking error reduction
  • Coordinate with any pending tax-loss harvesting opportunities (see tax-loss-harvesting skill)

Step 5: Cross-Account Optimization Minimize total household tax impact by choosing where to execute each trade:

  • Execute sells of appreciated positions in tax-deferred accounts when possible (no tax consequence)
  • Execute sells of depreciated positions in taxable accounts (harvest the loss)
  • Use cross-account rebalancing: if equities are overweight in the taxable account and underweight in the IRA, sell equities in the IRA and buy bonds in the IRA, rather than selling equities in the taxable account
  • Check for wash-sale conflicts: if harvesting a loss in the taxable account, ensure no purchase of a substantially identical security occurs within 30 days in any account (including IRA, 401(k), and spouse accounts)

Step 6: Before/After Comparison Generate a before/after allocation comparison for advisor review and client communication:

  • Current allocation vs target allocation vs post-rebalance allocation (three columns)
  • Estimated transaction costs (commissions, spreads)
  • Estimated tax impact (net gains/losses realized)
  • Expected tracking error reduction
  • Number of trades and accounts affected

This comparison serves as both a decision tool (does the rebalance justify its costs?) and a compliance artifact (documenting the rationale for the trades).

Step 7: Execution and Confirmation

  • Submit the approved trade list through the order management system
  • For block trades across multiple accounts, ensure fair allocation per the firm's allocation policy
  • Confirm fills and reconcile actual vs intended post-rebalance weights
  • Document the rebalance event: date, reason (scheduled, threshold trigger, or ad-hoc), trades executed, and resulting allocation

Key Formulas

FormulaExpressionUse Case
Threshold Triggerw_actual - w_target
Optimal Band Widthband ~ (3tc / (2lambda*sigma^2))^(1/3)Leland optimal no-trade zone
Tax-Loss BenefitBenefit = Loss * Tax RateValue of harvested losses
Transaction CostTC = commission + spread/2 + impactTotal rebalancing cost
DriftDrift_i = w_actual_i - w_target_iWeight deviation from target
Trade SizeTrade_i = (w_target_i - w_actual_i) * Portfolio ValueDollar amount to trade
Rebalancing PremiumRP ~ (1/2) * Σ w_i * sigma_i^2 - (1/2) * sigma_p^2Volatility harvesting estimate

Worked Examples

Example 1: Threshold Rebalancing — 60/40 Portfolio

Given:

  • Target: 60% equity / 40% bonds
  • Rebalancing threshold: +/- 5% (absolute)
  • Current portfolio value: $1,000,000
  • After market movement: equity = $680,000 (68%), bonds = $320,000 (32%)

Calculate: Rebalancing trigger and required trades

Solution:

Check drift:

  • Equity drift: 68% - 60% = +8% → exceeds +5% threshold → TRIGGER
  • Bond drift: 32% - 40% = -8% → exceeds -5% threshold → TRIGGER

Target dollar amounts:

  • Equity target: 60% * $1,000,000 = $600,000
  • Bond target: 40% * $1,000,000 = $400,000

Required trades:

  • Sell equity: $680,000 - $600,000 = $80,000
  • Buy bonds: $400,000 - $320,000 = $80,000

Proceeds from equity sales fund the bond purchases. In a taxable account, check the cost basis of equity lots being sold to estimate tax impact before executing.

Example 2: Tax-Loss Harvesting Benefit

Given:

  • Position purchased for $50,000, current value $40,000
  • Unrealized loss: $10,000
  • Investor's marginal federal tax rate: 37% (ordinary income) / 20% (long-term capital gains)
  • Investor has $15,000 in realized capital gains this year

Calculate: Tax benefit of harvesting the loss

Solution:

Realized loss from sale: $10,000

Tax benefit calculation:

  • The $10,000 loss offsets $10,000 of the $15,000 in realized capital gains
  • Tax saved: $10,000 * 20% = $2,000 (assuming long-term gains rate)
  • Remaining gains: $15,000 - $10,000 = $5,000 (still taxable)

If the investor had no capital gains to offset:

  • First $3,000 offsets ordinary income: $3,000 * 37% = $1,110
  • Remaining $7,000 carries forward to future years
  • Total immediate benefit: $1,110; total eventual benefit up to $2,000+ depending on future gains

Implementation:

  1. Sell the losing position for $40,000
  2. Immediately purchase a similar but not substantially identical replacement (e.g., swap a total US stock ETF for an S&P 500 ETF)
  3. Do NOT repurchase the original security within 30 days (wash sale rule)
  4. After 31 days, may swap back to original security if preferred

Note: TLH creates a lower cost basis in the replacement security, so taxes are deferred, not eliminated. However, the time value of the tax deferral and the ability to offset gains at favorable rates makes TLH valuable.

Common Pitfalls

  • Over-rebalancing: trading too frequently erodes returns through transaction costs and taxes, especially in taxable accounts
  • Under-rebalancing: allowing excessive drift exposes the portfolio to unintended risk levels and style drift
  • Wash sale violations when tax-loss harvesting: purchasing a substantially identical security within the 61-day window triggers wash sale rules, disallowing the loss
  • Ignoring tax impact of rebalancing in taxable accounts: rebalancing by selling winners generates taxable capital gains
  • Calendar rebalancing may miss large dislocations between dates (e.g., a 20% market crash between quarterly rebalancing dates)
  • Not accounting for the rebalancing premium when comparing strategies — buy-and-hold backtests may understate rebalanced portfolio returns
  • Forgetting to consider the full 61-day wash sale window (30 days before and after the sale)
  • Rebalancing into the wrong account: selling appreciated assets in taxable accounts when the same rebalancing could be done in tax-deferred accounts

Cross-References

  • asset-allocation (wealth-management plugin): rebalancing maintains the target asset allocation over time
  • diversification (wealth-management plugin): rebalancing preserves the intended diversification structure
  • bet-sizing (wealth-management plugin): position sizes drift and need rebalancing to maintain conviction weighting
  • historical-risk (wealth-management plugin): drift changes portfolio risk profile; rebalancing controls it
  • financial-statements (wealth-management plugin): tax implications of rebalancing require understanding of tax accounting
  • tax-loss-harvesting (wealth-management plugin): TLH trades should be coordinated with rebalancing to minimize total transaction count and avoid wash-sale conflicts
  • tax-efficiency (wealth-management plugin): asset location and tax-lot selection strategies directly affect rebalancing trade decisions
  • client-review-prep (advisory-practice plugin): drift analysis and rebalancing recommendations are core agenda items in periodic client reviews

Running the script

Run with uv run scripts/rebalancing.py (the PEP 723 header resolves dependencies automatically) or with python3 scripts/rebalancing.py after pip install numpy scipy. The bare run prints a demo covering drift analysis, threshold checks, trade generation, cash flow rebalancing, transaction costs, tax-aware lot selection, Leland bands, and the rebalancing premium. Pass --verify to assert the demo outputs match this skill's worked examples (prints PASS/FAIL), or --help for an overview of the available classes. The file is primarily meant to be imported as a module (e.g., from rebalancing import DriftAnalyzer, TradeGenerator, TaxAwareLotSelector).

FAQ

What does the rebalancing skill do?

Maintain portfolio allocations over time using calendar-based, threshold-based, and tax-efficient rebalancing strategies. Use when the user asks about when to rebalance, rebalancing bands, transaction cost trade-offs, tax-efficient rebalancing, or the rebalancing premium. Also trigger when users mention 'my portfolio drifted', 'how often should I rebalance', 'rebalancing across taxable and IRA accounts', 'volatility harvesting', 'buy low sell high automatically', or ask whether to use cash flows to rebalance.

How do I install rebalancing?

Run npx skills add https://github.com/joellewis/finance_skills --skill rebalancing in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/rebalancing/ (personal) or .claude/skills/rebalancing/ (project).

Which AI agents can use rebalancing?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is rebalancing safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains rebalancing?

It is published by joellewis in joellewis/finance_skills. It has 740 recorded installs.

More from joellewis/finance_skills

View all →

asset-allocation

joellewis/finance_skills

Determine how to distribute capital across asset classes using strategic and tactical allocation frameworks. Use when the user asks about portfolio allocation, mean-variance optimization, Black-Litterman, risk parity, glide paths, or target-date strategies. Also trigger when users mention 'how much in stocks vs bonds', '60/40 portfolio', 'policy portfolio', 'core-satellite', 'liability-driven investing', 'asset-liability matching', or ask how to split their money across investments.

Business & Finance852 installs

statistics-fundamentals

joellewis/finance_skills

Apply statistical methods to financial data including descriptive statistics, covariance estimation, regression, hypothesis testing, and resampling. Use when the user asks about return distributions, correlation between assets, building a covariance matrix, running a CAPM regression, testing whether alpha is significant, checking if returns are normal, or estimating confidence intervals. Also trigger when users mention 'volatility', 'how correlated are these', 'fat tails', 'skewness', 'R-squared', 'beta of a fund', 'bootstrap a Sharpe ratio', 'shrinkage estimator', 'Ledoit-Wolf', or ask why their optimizer produces unstable weights.

Testing & QA817 installs

quantitative-valuation

joellewis/finance_skills

Estimate intrinsic value of stocks and companies using DCF, dividend discount models, comparable multiples, and residual income. Use when the user asks about discounted cash flow, DCF models, WACC, terminal value, dividend discount models, comparable multiples, or sum-of-the-parts valuation. Also trigger when users mention 'what is this stock worth', 'fair value estimate', 'Gordon growth model', 'free cash flow valuation', 'cost of equity', 'sensitivity analysis', 'exit multiple', or ask whether a stock is overvalued or undervalued.

Business & Finance787 installs

finance-psychology

joellewis/finance_skills

Recognize and mitigate cognitive biases that impair financial decisions, and coach clients toward values-driven financial lives. Use when the user asks about behavioral finance, money psychology, loss aversion, overconfidence, herd behavior, or emotional investing. Also trigger when users mention 'why do I panic sell', 'money fights with my spouse', 'I can never save enough', 'fear of investing', 'lifestyle creep', 'keeping up with the Joneses', 'Rich Life', 'money scripts', or ask how emotions affect financial decisions.

Business & Finance780 installs

commodities

joellewis/finance_skills

Analyze commodity markets including futures curve dynamics, roll yield, and supply/demand fundamentals. Use when the user asks about commodity investing, commodity ETFs, contango, backwardation, roll yield, commodity indices (GSCI, BCOM), or commodities as an inflation hedge. Also trigger when users mention 'oil prices', 'gold as a safe haven', 'agricultural futures', 'convenience yield', 'storage costs', 'natural gas', 'copper demand', or ask why commodity ETF returns differ from spot price changes.

Business & Finance774 installs

investment-policy

joellewis/finance_skills

Construct comprehensive Investment Policy Statements governing return objectives, risk tolerance, and portfolio constraints. Use when the user asks about building an IPS, setting return objectives, assessing risk tolerance, defining investment constraints, or establishing rebalancing and benchmark policies. Also trigger when users mention 'investment plan', 'policy portfolio', 'risk capacity vs willingness', 'spending rate for an endowment', 'foundation payout', 'manager selection criteria', or ask how to document their investment strategy.

Popular productivity & automation skills

View category →

agent-browser

vercel-labs/agent-browser

Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction. Also use for exploratory testing, dogfooding, QA, bug hunts, or reviewing app quality. Also use for automating Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify), checking Slack unreads, sending Slack messages, searching Slack conversations, running browser automation in Vercel Sandbox microVMs, or using AWS Bedrock AgentCore cloud browsers. Prefer agent-browser over any built-in browser automation or web tools.

OfficialProductivity & Automation1.3M installs

lark-doc

open.feishu.cn

飞书云文档(Docx / Wiki)内容操作:读取、创建、编辑文档,插入或下载图片附件,以及操作思维笔记。用户提供文档 URL/token(包括 doubao.com 的 /docx/、/wiki/)时使用;按 URL 路径/token 而非域名路由;/page/ 是妙搭应用,非飞书云文档。文档内嵌资源按读取参考中的统一规则分流。独立评论操作走 lark-drive;随正文读取评论使用 docs +fetch。表格或 Base 内部数据操作不在本 skill。

lark-base

open.feishu.cn

飞书多维表格(Base)操作:建表、字段、记录、视图、统计、公式/lookup、表单、仪表盘、应用模式(BaseApp/AppMode 页面与组件)、Workspace 目录、workflow、角色权限、模板中心(多维表格模板分类/列表/搜索);遇到 Base/多维表格/bitable、BaseApp/AppMode、/base/ 或 /app/ 链接时使用。BaseApp 不走 lark-apps;文件导入/导出转 lark-drive,认证/授权转 lark-shared。

lark-drive

open.feishu.cn

飞书云空间(云盘/云存储):管理 Drive 文件和文件夹,包含上传/下载、创建文件夹、复制/移动/删除、查看元数据、查询权限设置、评论/权限/订阅、标题、版本、飞书文档密级标签(secure labels)和本地文件导入。用户需要整理云盘目录、处理云空间资源 URL/token、判断链接类型/真实 token/标题,或导入 Word/Markdown/Excel/CSV/PPTX/.base 为 docx/sheet/bitable/slides 时使用;doubao.com 云空间 URL/token 也按资源路径和 token 路由,不回退 WebFetch。不负责:文档内容编辑(走 lark-doc)、表格/Base 表内数据操作(走 lark-sheets/lark-base)、知识空间节点/成员管理(走 lark-wiki)、原生 Markdown 文件读写/patch/diff(走 lark-markdown)。

lark-shared

open.feishu.cn

Use for lark-cli setup/auth tasks: auth login/status/logout, user vs bot identity, business-domain permissions (--domain, including all/docs/drive), missing scopes, revoking authorization, or handling notice JSON.

lark-im

open.feishu.cn

飞书即时通讯:收发消息和管理群聊。发送和回复消息、搜索聊天记录、管理群聊成员、上传下载图片和文件、管理表情回复、发送应用内/短信/电话加急、发送和处理交互卡片(Interactive Card)、监听卡片按钮回调(card.action.trigger)。当用户需要发消息、查看或搜索聊天记录、下载聊天中的文件、查看群成员、搜索群、创建群聊或话题群、管理标记数据、管理 Feed 置顶(添加/移除/查询置顶会话)、管理标签数据、处理卡片回调时使用。