DEV Community

soy
soy

Posted on

[03] Designing a Personal Commitment Line — Two Loans, One Defense System

[03] Designing a Personal Commitment Line — Two Loans, One Defense System

This is Part 3 of a 6-part series: Building Investment Systems with Python


The Corporate Playbook

Every major corporation maintains a revolving credit facility — a pre-arranged borrowing line they can draw from instantly during a crisis. They pay a commitment fee for the privilege of having this standby capacity, even when they don't use it.

The logic is simple: the time you most need to borrow is exactly when borrowing becomes hardest.

This applies to individuals too. A securities-backed loan shrinks when your portfolio drops. You need a second source — one that's independent of market conditions.


Correlated vs. Orthogonal Defense

This is the most important concept in the series.

# defense_types.py
from dataclasses import dataclass
from typing import Optional

@dataclass
class Loan:
    name: str
    balance: float
    rate: float
    collateral_value: Optional[float]  # None = unsecured
    freeze_ratio: Optional[float]
    call_ratio: Optional[float]
    liq_ratio: Optional[float]

    def available_at_drawdown(self, drawdown_pct: float) -> float:
        """How much of this loan's balance is still accessible after a drawdown?"""
        if self.collateral_value is None:
            # Unsecured — always available regardless of market
            return self.balance

        # Collateral-based — capacity shrinks with market
        new_collateral = self.collateral_value * (1 - drawdown_pct)
        if self.freeze_ratio and (self.balance / new_collateral) > self.freeze_ratio:
            return 0  # Frozen — can't borrow more
        return self.balance

    def repay_needed(self, drawdown_pct: float, target_ratio: float = 0.65) -> float:
        """How much must be repaid to restore target ratio after drawdown?"""
        if self.collateral_value is None:
            return 0  # No margin requirements

        new_collateral = self.collateral_value * (1 - drawdown_pct)
        target_balance = new_collateral * target_ratio
        return max(0, self.balance - target_balance)


def compare_strategies():
    portfolio = 125_000_000

    # Strategy A: All margin, no orthogonal defense
    strategy_a = [
        Loan("margin_only", 58_000_000, 0.02, portfolio, 0.60, 0.70, 0.85),
    ]

    # Strategy B: Lower margin + orthogonal credit line
    strategy_b = [
        Loan("margin", 50_000_000, 0.02, portfolio, 0.60, 0.70, 0.85),
        Loan("credit_line", 8_000_000, 0.0225, None, None, None, None),
    ]

    print(f"{'Drawdown':>10} {'Strategy A (¥58M margin)':>28} {'Strategy B (¥50M + ¥8M credit)':>32}")
    print(f"{'':>10} {'Repay to survive':>28} {'Repay to survive':>32}")
    print("" * 72)

    for drop in range(0, 70, 5):
        pct = drop / 100

        # Strategy A
        a_collateral = portfolio * (1 - pct)
        a_ratio = 58_000_000 / a_collateral if a_collateral > 0 else float('inf')
        a_repay = max(0, 58_000_000 - a_collateral * 0.85)
        a_status = "💀" if a_repay > 0 and a_ratio > 0.85 else ""

        # Strategy B
        b_collateral = portfolio * (1 - pct)
        b_ratio = 50_000_000 / b_collateral if b_collateral > 0 else float('inf')
        b_repay = max(0, 50_000_000 - b_collateral * 0.85)
        b_defense = 8_000_000  # credit line available for repayment
        b_status = "" if b_repay <= b_defense else "💀"

        print(f"  -{drop:>3}%   ¥{a_repay:>12,.0f} {a_status:>6}        ¥{b_repay:>12,.0f} {b_status:>6}")

    print()
    print("Same total borrowed (¥58M). Radically different outcomes.")
    print("The ¥8M credit line acts as an 'airbag' — orthogonal to the crash.")

if __name__ == "__main__":
    compare_strategies()
Enter fullscreen mode Exit fullscreen mode

The Cost Optimizer

The question isn't just "should I have a credit line?" — it's "what's the optimal split between margin debt and unsecured credit to minimize cost while maximizing survival?"

# optimize_defense.py
import sqlite3
from alm_schema import DB_PATH

def optimize_loan_structure(
    total_needed: float,
    portfolio_value: float,
    margin_rate: float = 0.02,
    credit_rate: float = 0.0225,
    target_survival: float = 0.60,  # survive a -60% drawdown
):
    """
    Find the minimum-cost loan split that survives the target drawdown.

    The margin loan is cheaper but correlated with the portfolio.
    The credit line is slightly more expensive but orthogonal.
    """

    results = []

    # Try every possible split in ¥1M increments
    for margin_amount in range(0, int(total_needed) + 1, 1_000_000):
        credit_amount = total_needed - margin_amount

        # Annual cost
        annual_cost = margin_amount * margin_rate + credit_amount * credit_rate

        # Stress test: can this survive target_survival drawdown?
        stressed_collateral = portfolio_value * (1 - target_survival)

        # Margin ratio after drawdown
        if stressed_collateral <= 0:
            continue
        margin_ratio = margin_amount / stressed_collateral

        # Repayment needed to avoid forced liquidation (85%)
        repay_needed = max(0, margin_amount - stressed_collateral * 0.85)

        # Can the credit line cover the repayment?
        survives = repay_needed <= credit_amount

        # Margin ratio at rest (no drawdown)
        rest_ratio = margin_amount / portfolio_value

        results.append({
            'margin': margin_amount,
            'credit': credit_amount,
            'annual_cost': annual_cost,
            'rest_ratio': rest_ratio,
            'stressed_ratio': margin_ratio,
            'repay_needed': repay_needed,
            'survives': survives,
        })

    # Filter survivors and sort by cost
    survivors = [r for r in results if r['survives']]

    if not survivors:
        print("No configuration survives the target drawdown.")
        return

    survivors.sort(key=lambda x: x['annual_cost'])

    print(f"Target: Survive -{target_survival:.0%} drawdown")
    print(f"Portfolio: ¥{portfolio_value:,.0f}")
    print(f"Total borrowing: ¥{total_needed:,.0f}")
    print(f"Margin rate: {margin_rate:.2%} | Credit rate: {credit_rate:.2%}")
    print()
    print(f"{'Margin':>12} {'Credit':>12} {'Cost/yr':>10} {'Rest %':>8} "
          f"{'Stress %':>10} {'Repay':>12}")
    print("" * 70)

    for r in survivors[:10]:  # Top 10 cheapest
        print(f"¥{r['margin']:>10,.0f} ¥{r['credit']:>10,.0f} "
              f"¥{r['annual_cost']:>8,.0f} {r['rest_ratio']:>7.1%} "
              f"{r['stressed_ratio']:>9.1%} ¥{r['repay_needed']:>10,.0f}")

    best = survivors[0]
    print()
    print(f"✅ Optimal: ¥{best['margin']:,.0f} margin + ¥{best['credit']:,.0f} credit")
    print(f"   Annual cost: ¥{best['annual_cost']:,.0f}")
    print(f"   Margin ratio at rest: {best['rest_ratio']:.1%}")

if __name__ == "__main__":
    optimize_loan_structure(
        total_needed=58_000_000,
        portfolio_value=125_000_000,
    )
Enter fullscreen mode Exit fullscreen mode

The Alert System

Set up automatic alerts when your margin ratio approaches danger zones.

# margin_alert.py
import sqlite3
from datetime import date
from alm_schema import DB_PATH

THRESHOLDS = {
    'green':  0.50,   # comfortable
    'yellow': 0.55,   # attention
    'orange': 0.60,   # freeze imminent
    'red':    0.70,   # margin call territory
}

def check_margin_status():
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()

    c.execute("""
        SELECT SUM(h.shares * p.close_price)
        FROM holdings h
        JOIN prices p ON h.ticker = p.ticker
        WHERE p.price_date = (SELECT MAX(price_date) FROM prices)
    """)
    portfolio = c.fetchone()[0]

    c.execute("SELECT SUM(balance) FROM loans WHERE collateral_type = 'portfolio'")
    margin_balance = c.fetchone()[0]
    conn.close()

    ratio = margin_balance / portfolio

    if ratio < THRESHOLDS['green']:
        status = "🟢 COMFORTABLE"
        action = "No action needed."
    elif ratio < THRESHOLDS['yellow']:
        status = "🟡 ATTENTION"
        action = "Monitor daily. Consider reducing if trend continues."
    elif ratio < THRESHOLDS['orange']:
        status = "🟠 WARNING"
        action = "Prepare cash for potential repayment. New borrowing may freeze."
    else:
        status = "🔴 CRITICAL"
        repay = margin_balance - portfolio * 0.60
        action = f"Repay ¥{repay:,.0f} to restore to 60%. Consider using credit line."

    report = f"""
[{date.today()}] MARGIN STATUS: {status}
  Portfolio:    ¥{portfolio:>14,.0f}
  Margin Loan:  ¥{margin_balance:>14,.0f}
  Ratio:          {ratio:>12.1%}
  Action:       {action}
"""
    print(report)
    return ratio, status

if __name__ == "__main__":
    check_margin_status()
Enter fullscreen mode Exit fullscreen mode

Wire this to cron. Get an alert every evening. Sleep well.


What We Built

  • A correlated vs. orthogonal defense comparison tool
  • A cost optimizer that finds the cheapest loan split for your target survival rate
  • An automated margin status alert system
  • The conceptual framework: orthogonal defense > correlated defense

Next week: [04] Dividend Snowball Simulator — "DOE: dividends that grow themselves."


Series: Building Investment Systems with Python — Engineering financial independence with code.

Top comments (0)