Calculates margin strategy metrics from Fidelity data and alerts users when draws exceed defined safety or income limits.

Install

mkdir -p .claude/skills/margin-management && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/3974" && unzip -o skill.zip -d .claude/skills/margin-management && rm skill.zip

Installs to .claude/skills/margin-management

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Update Margin Dashboard with Fidelity balance data and calculate margin-living strategy metrics. Monitors margin balance, interest costs, coverage ratios, and scaling thresholds. Triggers safety alerts for large draws and provides time-based scaling recommendations. Use when updating margin, balances, coverage ratio, or margin strategy analysis.
347 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Intermediate

Key capabilities

  • Sync live margin balances from SnapTrade
  • Calculate dividend coverage and portfolio-to-margin ratios
  • Trigger safety alerts for large margin draws
  • Provide time-based scaling recommendations
  • Update margin dashboard with interest and balance metrics

How it works

The tool reads live portfolio data from SnapTrade, calculates strategy metrics like coverage ratios, and updates a Google Sheet while checking against predefined safety thresholds.

Inputs & outputs

You give it
Live margin balance data from SnapTrade
You get back
Updated margin dashboard metrics and scaling alerts

When to use margin-management

  • Calculate portfolio margin coverage ratios
  • Update margin dashboard with new balances
  • Monitor monthly margin interest costs
  • Check margin safety thresholds

About this skill

Margin Management

Purpose

Monitor and manage margin-living strategy by tracking margin balances, interest costs, dividend coverage ratios, and portfolio-to-margin safety thresholds. Provides data-driven scaling recommendations based on strategy milestones.

Step 0: Refresh (sync-first, mandatory)

This skill reads margin facts from the local DB, and the DB is refreshed FIRST so it can never be stale. Follow the shared Sync-First + DB-Read pattern. Minimum for this skill (positions + balances into the balances table):

uv run python -m src.integrations.snaptrade.sync_db   # or: refresh_all

Completion criterion: the balances table carries this run's synced_at before any margin number is read.

When to Use

Use this skill when:

  • Syncing live margin balances from SnapTrade
  • Updating margin balance or interest rate
  • Calculating coverage ratio (dividends ÷ interest)
  • User mentions: "margin dashboard", "margin balance", "coverage ratio", "margin strategy"
  • Assessing margin scaling decisions
  • Checking safety thresholds

Personal Strategy Inputs

Static private assumptions come from .env (see .env.example). Current portfolio facts come from the local DB balances snapshot (refreshed sync-first in Step 0), then src/analysis/margin_metrics.py derives ratios/costs at runtime. Do not hardcode personal numbers in this skill. Fallbacks: --source snaptrade reads the API live, --source csv reads the legacy Fidelity balances CSV.

Required .env values

  • FG_STRATEGY_START_DATE
  • FG_MARGIN_INTEREST_RATE, FG_MARGIN_INTEREST_RATE_DECIMAL
  • FG_MARGIN_JUMP_ALERT_THRESHOLD
  • FG_CURRENT_MONTHLY_DRAW, FG_MONTH6_DRAW_TARGET, FG_MONTH12_DRAW_TARGET, FG_MONTH18_DRAW_TARGET
  • FG_BUSINESS_INCOME_MONTHLY, FG_BUSINESS_INJECTION_RED, FG_BUSINESS_INJECTION_CRITICAL
  • Live facts are not .env values: portfolio value, margin balance, interest cost, dividend income, coverage ratio, and portfolio-to-margin ratio must be read/calculated at runtime.

Core Workflow

1. Read Margin Balances (local DB snapshot)

After Step 0's refresh, run uv run python -m src.analysis.margin_metrics --pretty. It loads .env, reads the latest balances row from family_office.db (the db source is the default), and emits current JSON metrics. Fallbacks if needed: --source snaptrade (live API) or --source csv (latest Balances_for_Account_*.csv).

Source: the balances table, written by the Step 0 sync from the enabled+routed SnapTrade account in config/snaptrade-accounts.yaml (enabled: true, role set). Requires SNAPTRADE_* keys in .env for the refresh.

Key JSON fields the tool emits:

  • portfolio_value → net account equity (account_equity) → Portfolio Value
  • margin_balance → derived margin debt (gross market value minus net equity) → Margin Balance
  • monthly_interest_cost → Balance × Rate ÷ 12 (the primary interest figure)
  • margin_interest_accrued_this_monthnull on the DB and SnapTrade paths (the broker does not expose accrued interest; it is only present via --source csv)

Calculations:

  • Margin Balance: Derived margin debt = {live.margin_balance} (tracks Fidelity "Net debit" within ~0.1%)
  • Interest Rate: Default ${FG_MARGIN_INTEREST_RATE} (Fidelity $1k-$24.9k tier) unless specified
  • Monthly Interest Cost: Balance × Rate ÷ 12 = {live.margin_balance} × ${FG_MARGIN_INTEREST_RATE_DECIMAL} ÷ 12 = {derived.monthly_interest_cost}

2. Safety Check: Margin Jump Alert

Rule: If new margin balance > previous balance + ${FG_MARGIN_JUMP_ALERT_THRESHOLD}, STOP

Reason: Large draws should be intentional per margin-living strategy

Example:

Previous: {live.margin_balance}
Current: {example.margin_current} (+{derived.margin_increase}) → 🚨 ALERT - Confirm intentional draw

Action:

  • Alert user immediately
  • Show diff: "Margin increased by {derived.margin_increase} - Confirm this was intentional"
  • Wait for user confirmation before proceeding

3. Report the current snapshot

There is nowhere to write an entry: balances is a current-state table keyed on account_id, so each sync overwrites the prior row and no ledger accumulates. Report the snapshot in the response instead.

  • Date: current date (use date +"%Y-%m-%d")
  • Margin Balance: margin_debt from the balances row
  • Interest Rate: ${FG_MARGIN_INTEREST_RATE}
  • Monthly Interest Cost: Balance × Rate ÷ 12
  • Elapsed: months since ${FG_STRATEGY_START_DATE}, which selects the scaling tier below

4. Derived metrics

Monthly Interest Cost

margin_debt × ${FG_MARGIN_INTEREST_RATE} ÷ 12

Annual Interest Cost

monthly_interest_cost × 12

Dividend Income

Sum type = 'DIVIDEND' rows in transactions for the trailing month. See the dividend-tracking skill; do not recompute its aggregation differently here.

Coverage Ratio

monthly_dividend_income ÷ monthly_interest_cost

Guard the zero case: when margin_debt is 0 there is no interest to cover, so report coverage as not-applicable rather than dividing.

5. Calculate Strategy Metrics

Portfolio-to-Margin Ratio

= Total account value ÷ Margin Balance
Example: {live.portfolio_value} ÷ {live.margin_balance} = {derived.portfolio_margin_ratio} 🟢🟢🟢

Safety Thresholds:

  • 🟢 Green: Ratio > 4.0:1 (target - healthy margin usage)
  • 🟡 Yellow: Ratio 3.5-4.0:1 (warning - pause scaling)
  • 🔴 Red: Ratio < 3.0:1 (alert - stop draws, inject business income)
  • Critical: Ratio < 2.5:1 (emergency - inject ${FG_BUSINESS_INJECTION_CRITICAL}, consider selling)

Current Draw vs Fixed Expenses

Current monthly draw: ${FG_CURRENT_MONTHLY_DRAW} (fixed expenses only)
Target: Start with ${FG_CURRENT_MONTHLY_DRAW}, scale to ${FG_MONTH6_DRAW_TARGET}, ${FG_MONTH12_DRAW_TARGET}, ${FG_MONTH18_DRAW_TARGET} based on data

6. Scaling Alerts (Time-Based)

Strategy Start Date: ${FG_STRATEGY_START_DATE}

Calculate months elapsed:

import os
from datetime import datetime

start = datetime.fromisoformat(os.getenv("FG_STRATEGY_START_DATE"))
current = datetime.now()
months_elapsed = (current - start).days // 30

Month 6 Alert

📊 MONTH 6 MILESTONE CHECK:
✅ Dividends: {live.monthly_dividend_income}/month (need ${FG_MONTH6_DIVIDEND_MINIMUM})
✅ Portfolio-to-Margin Ratio: {derived.portfolio_margin_ratio} (need 4:1+)
✅ Dividend Growth: On track

🎯 RECOMMENDATION: Scale margin draw to ${FG_MONTH6_DRAW_TARGET}/month (add mortgage)
- Current: ${FG_CURRENT_MONTHLY_DRAW} (fixed expenses only)
- New: ${FG_MONTH6_DRAW_TARGET} (fixed + mortgage)
- Safety margin: Excellent

Month 12 Alert

📊 MONTH 12 BREAK-EVEN CHECK:
Expected Dividends: ${FG_MONTH12_DIVIDEND_TARGET}/month (goal: break-even with margin interest)
✅ IF achieved: Consider scaling to ${FG_MONTH12_DRAW_TARGET}/month (add some variable expenses)
⚠️ IF not: Hold at ${FG_MONTH6_DRAW_TARGET}, assess strategy

Month 18 Alert

📊 MONTH 18 MATURE STRATEGY CHECK:
Expected Dividends: ${FG_MONTH18_DIVIDEND_TARGET}/month
Expected Margin: Declining (dividends paying down debt)
✅ IF achieved: Consider scaling to ${FG_MONTH18_DRAW_TARGET}/month (most variable expenses)
⚠️ IF not: Hold current level, reassess timeline

7. Alert Thresholds

Generate alerts based on conditions:

Green (Healthy)

✅ Ratio > 4:1 AND dividends covering interest
Status: On track, continue per strategy

Yellow (Caution)

⚠️ Ratio 3.5-4:1 OR dividend coverage declining
Action: Pause scaling, monitor weekly

Red (Alert)

🚨 Ratio < 3:1 OR dividend cuts detected
Action: STOP draws, inject ${FG_BUSINESS_INJECTION_RED} business income

Critical (Emergency)

⛔ Ratio < 2.5:1 OR margin call risk
Action: STOP draws, inject ${FG_BUSINESS_INJECTION_CRITICAL} business income, consider selling hedge (SQQQ)

Critical Rules

This skill is read-only

family_office.db is written by the sync CLIs alone. Never hand-edit rows to make a metric look right; fix the sync that wrote the bad row instead.

Margin Strategy Philosophy

Core Principle: Confidence-based scaling, not time-based mandates

Decision Framework:

  1. Data-driven: Decisions backed by actual dividend income, not projections
  2. Safety-first: Never scale if ratio drops below 3.5:1
  3. Business income as insurance: Available ${FG_BUSINESS_INCOME_MONTHLY}/month, not primary strategy
  4. Monte Carlo backstop: ${FG_BUSINESS_BACKSTOP_PROBABILITY} of scenarios used business income at some point

Business Income Backstop

Available: ${FG_BUSINESS_INCOME_MONTHLY}/month from business operations

Usage Scenarios:

  1. Margin call (ratio < 3:1): MUST USE business income immediately
  2. ⚠️ Market correction (20-30% drop): OPTIONAL - assess need
  3. 🎯 Acceleration (reach FI faster): OPTIONAL - strategic choice

Current Philosophy: Insurance policy only, not active strategy component

Example Calculations

Scenario 1: Month 1 (Current State)

Portfolio Value: {live.portfolio_value}
Margin Balance: {live.margin_balance}
Ratio: {derived.portfolio_margin_ratio} 🟢🟢🟢

Monthly Interest: {derived.monthly_interest_cost}
Dividend Income: {live.monthly_dividend_income}
Coverage: {derived.coverage_ratio} 🟢

Status: Excellent - building foundation

Scenario 2: Month 6 (Projected)

Portfolio Value: {projection.month6_portfolio_value} (projected with W2 contributions)
Margin Balance: {projection.month6_margin_balance} (scaled to ${FG_MONTH6_DRAW_TARGET}/month draw)
Ratio: {projection.month6_portfolio_margin_ratio} 🟢

Monthly Interest: {projection.month6_monthly_interest_cost}
Dividend Income: ${FG_CURRENT_MONTHLY_DRAW} (projected)
Coverage: {projection.month6_coverage_ratio} 🟢

Status: Healthy - on track for break-even

Scenario 3: Month 15 (Break-Eve


Content truncated.

When not to use it

  • When the user has not configured SnapTrade accounts
  • When the user expects automated trading execution

Prerequisites

SnapTrade account enabled in config/snaptrade-accounts.yamlRequired environment variables in .envDividend Tracker must be up-to-date

Limitations

  • Cannot modify summary formulas without the Builder skill
  • SnapTrade must be enabled and routed for live data

How it compares

This workflow automates the calculation of margin-living strategy metrics and safety checks that would otherwise require manual spreadsheet updates and formula maintenance.

Compared to similar skills

margin-management side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
margin-management (this skill)13moReviewIntermediate
quant-analyst1032moNo flagsAdvanced
stock-analyzer712moReviewBeginner
pair-trade-screener111moReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by AojdevStudio

View all by AojdevStudio

financereport

AojdevStudio

Generate institutional-quality PDF analysis reports for stocks and ETFs. USE WHEN user mentions generate report, create pdf, stock analysis, ticker report, watchlist analysis, OR regenerate reports. Includes VGT-style headers, embedded charts, portfolio sizing, and Perplexity sentiment integration.

636

portfoliosyncing

AojdevStudio

Import and sync broker CSV portfolio data to Google Sheets DataHub. Supports multiple brokers (Fidelity, Schwab, Vanguard, etc.). USE WHEN user mentions import broker data OR sync portfolio OR update positions OR CSV import OR portfolio-sync OR working with Portfolio_Positions CSVs. Handles position updates, SPAXX/margin validation, safety checks, and formula protection.

333

formula-protection

AojdevStudio

Prevent accidental modification of sacred spreadsheet formulas in Google Sheets Portfolio Tracker. Blocks edits to GOOGLEFINANCE formulas, calculated columns, and total rows. Allows only IFERROR wrappers, fixing broken references, and expanding ranges. Triggers on update formula, modify column, fix errors, or any attempt to edit formula-based cells.

14

montecarlo

AojdevStudio

Run Monte Carlo simulations for Finance Guru portfolio strategy. USE WHEN user mentions monte carlo OR run simulation OR stress test portfolio OR probability analysis OR income projections OR margin safety analysis. Supports 4-layer portfolio (Growth, Income, Hedge, GOOGL) with auto-detection of current values from Fidelity CSV.

15

retirement-syncing

AojdevStudio

Sync retirement account data from Vanguard and Fidelity CSV exports to Google Sheets DataHub. Handles multiple accounts, aggregates holdings by ticker, and updates quantities in retirement section (rows 46-62). Triggers on sync retirement, update retirement, vanguard sync, 401k update, IRA sync, or working with notebooks/retirement-accounts/ files.

15

transactionsyncing

AojdevStudio

Import Fidelity transaction history CSV into Google Sheets with smart categorization. USE WHEN user mentions "sync transactions", "import transactions", "transaction history", OR wants to import Fidelity History CSV. Routes debit card purchases to Expense Tracker with auto-categorization.

110

You might also like

quant-analyst

zenobi-us

Expert quantitative analyst specializing in financial modeling, algorithmic trading, and risk analytics. Masters statistical methods, derivatives pricing, and high-frequency trading with focus on mathematical rigor, performance optimization, and profitable strategy development.

103355

stock-analyzer

FrancyJGLisboa

Provides comprehensive technical analysis for stocks and ETFs using RSI, MACD, Bollinger Bands, and other indicators. Activates when user requests stock analysis, technical indicators, trading signals, or market data for specific ticker symbols.

71214

pair-trade-screener

tradermonty

Statistical arbitrage tool for identifying and analyzing pair trading opportunities. Detects cointegrated stock pairs within sectors, analyzes spread behavior, calculates z-scores, and provides entry/exit recommendations for market-neutral strategies. Use when user requests pair trading opportunities, statistical arbitrage screening, mean-reversion strategies, or market-neutral portfolio construction. Supports correlation analysis, cointegration testing, and spread backtesting.

1198

risk-metrics-calculation

wshobson

Calculate portfolio risk metrics including VaR, CVaR, Sharpe, Sortino, and drawdown analysis. Use when measuring portfolio risk, implementing risk limits, or building risk monitoring systems.

881

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

model-usage

openclaw

Use CodexBar CLI local cost usage to summarize per-model usage for Codex or Claude, including the current (most recent) model or a full model breakdown. Trigger when asked for model-level usage/cost data from codexbar, or when you need a scriptable per-model summary from codexbar cost JSON.

548

Search skills

Search the agent skills registry