portfolio-leverage-calculator Svelte Themes

Portfolio Leverage Calculator

Portfolio leverage calculator with Svelte dashboard and Interactive Brokers integration via IBeam

Portfolio Leverage Calculator

A clean, modular Python application for calculating portfolio leverage and implied financing rates using Interactive Brokers data via IBeam's Client Portal Web API.

๐Ÿš€ Features

  • Clean Architecture: Separation of data access, business logic, and presentation layers
  • IBeam Integration: Uses IBeam's REST API for reliable Interactive Brokers connectivity
  • Portfolio Analysis: Calculates leverage ratios with detailed position analysis
  • Implied Rate Calculator: Calculates effective financing costs of deep ITM LEAPS using academic models
  • Historical Dividend Data: 5-year average dividend yields for accurate calculations
  • Comprehensive Testing: Unit tests and integration tests with mock data providers
  • Docker Support: Containerized deployment with IBeam

๐Ÿ—๏ธ Architecture

src/
โ”œโ”€โ”€ portfolio_leverage/
โ”‚   โ”œโ”€โ”€ data_providers/          # Data Access Layer
โ”‚   โ”‚   โ”œโ”€โ”€ interfaces.py        # Abstract interfaces
โ”‚   โ”‚   โ”œโ”€โ”€ models.py           # Data models (Position, AccountInfo, MarketData)
โ”‚   โ”‚   โ””โ”€โ”€ ibeam_data_provider.py  # IBeam REST API implementation
โ”‚   โ””โ”€โ”€ calculators/            # Business Logic Layer
โ”‚       โ””โ”€โ”€ leverage_calculator.py  # Leverage calculation logic
โ””โ”€โ”€ main.py                     # Application Entry Point

tests/
โ”œโ”€โ”€ test_leverage.py           # Unit tests with mock data
โ”œโ”€โ”€ test_ibeam_integration.py  # Integration tests with IBeam
โ””โ”€โ”€ test_ibeam_api.py         # IBeam API connectivity tests

๐Ÿ“Š Leverage Calculation

The calculator uses the following formulas:

1. Time to Expiry (T)

T = (expiry_date - today) / 365.25  # Years to expiration (precise)

2. Position Exposure (E)

E = delta * S * contracts * 100  # For options (100 shares per contract)
E = quantity * current_price     # For stocks

3. Portfolio Leverage

Portfolio Leverage = Total Exposure / Net Liquidation Value

๐Ÿ’ฐ Implied Interest Rate Calculator

The application includes a sophisticated Implied Rate Calculator that determines the effective financing cost embedded in deep in-the-money (DITM) LEAPS using rigorous academic models.

Mathematical Foundation

Based on put-call parity with dividend adjustments, the calculator implements two primary methods:

Method 1: Continuous Dividend Model (better for index options)

# From put-call parity: C - P = S*e^(-qT) - K*e^(-rT)
# For deep ITM calls where P โ‰ˆ 0: C โ‰ˆ S*e^(-qT) - K*e^(-rT)
# Solving for r:
r = -(1/T) * ln((S*e^(-qT) - C) / K)

Method 2: Discrete Dividend Model (better for stock options)

# With discrete dividends: C โ‰ˆ S - D - K*e^(-rT)
# Where D = PV(dividends) = ฮฃ(d_i * e^(-r*t_i))
# Solving iteratively for r:
r = -(1/T) * ln((S - C - D) / K)

Key Variables

  • S = Current underlying stock price
  • C = Call option price per share
  • K = Strike price
  • T = Time to expiration (years)
  • q = Continuous dividend yield
  • D = Present value of discrete dividends
  • r = Implied interest rate (what we solve for)

Academic References

  • Ayres & Nalebuff (2008): "Lifecycle Investing and Leverage"
  • Put-call parity theory with dividend adjustments
  • Academic literature on LEAPS financing costs

Dividend Yield Data

The calculator uses 5-year historical average dividend yields for major assets:

Asset 5-Year Avg Yield Type
SPY 1.78% S&P 500 ETF
QQQ 0.68% NASDAQ ETF
IWM 1.42% Russell 2000 ETF
AAPL 0.62% Individual Stock
MSFT 0.72% Individual Stock
AMZN 0.00% Non-dividend paying

Example Calculation

For a realistic SPY LEAPS scenario:

# Parameters: SPY at $620, $400 strike call, $22 option price, 1.5 years
S = 620.0      # Current SPY price
K = 400.0      # Strike price  
C = 22.0       # Option price per share
T = 1.5        # Time to expiry (years)
q = 0.0178     # SPY 5-year avg dividend yield

# Calculate implied rate
S_adjusted = S * np.exp(-q * T)  # = 620 * e^(-0.0178*1.5) โ‰ˆ 603.7
numerator = S_adjusted - C       # = 603.7 - 22.0 = 581.7
r = -(1/T) * np.log(numerator / K)  # = -(1/1.5) * ln(581.7/400) โ‰ˆ -0.25%

# Result: Implied financing rate โ‰ˆ -0.25% (below risk-free rate!)

Confidence Levels

The calculator assigns confidence levels based on option characteristics:

  • High Confidence: Deep ITM (moneyness > 1.25), low time value (<5% of intrinsic), long-term (>6 months)
  • Medium Confidence: ITM (moneyness > 1.15), moderate time value (<10% of intrinsic), medium-term (>3 months)
  • Low Confidence: All other scenarios

Interpretation

Negative rates indicate that the LEAPS are providing below-market financing, making them an efficient leveraging tool.

Positive rates show the total cost of leverage including dividends and time value.

Rates are compared against the risk-free rate (default 5%) to assess relative value.

๐Ÿ”ง Setup

Prerequisites

  • Python 3.10+
  • Docker and Docker Compose
  • Interactive Brokers account
  • IBeam for API access

Installation

  1. Clone the repository

    git clone <repository-url>
    cd options
    
  2. Install Python dependencies

    pip install -r requirements.txt
    # Or install as a package
    pip install -e .
    
  3. Set up environment variables

    # Create .env file
    IBKR_USERNAME=your_username
    IBKR_PASSWORD=your_password  
    IBKR_TRADING_MODE=live  # or 'paper'
    
  4. Start IBeam

    docker-compose up -d
    
  5. Authenticate with IBeam

    • Open https://localhost:5500 in your browser
    • Complete the Interactive Brokers login process
    • Handle 2FA authentication if required

๐Ÿš€ Usage

Command Line Interface

# Run the main application
cd src
python main.py

# Choose execution mode:
# 1. Run with IBeam (requires authentication)
# 2. Run with Mock Data (for testing)
# 3. Exit

Web Dashboard (Svelte + FastAPI + Docker)

# One-click using Makefile
make up

# Open the dashboard
open http://localhost:8080

# If first run, authenticate IBeam once in the browser
open https://localhost:5500

Programmatic Usage

import asyncio
from portfolio_leverage.data_providers import IBeamDataProvider
from portfolio_leverage.calculators.leverage_calculator import LeverageCalculator

async def calculate_leverage():
    # Initialize data provider
    provider = IBeamDataProvider(base_url="https://localhost:5500")
    
    # Create calculator
    calculator = LeverageCalculator(provider)
    
    # Calculate leverage
    df, leverage_ratio = await calculator.calculate_leverage()
    
    print(f"Portfolio Leverage: {leverage_ratio:.3f}")
    return df, leverage_ratio

# Run the calculation
asyncio.run(calculate_leverage())

๐Ÿงช Testing

Run Unit Tests

cd tests
python test_leverage.py

Run Integration Tests (requires IBeam)

cd tests  
python test_ibeam_integration.py

Test IBeam API Connectivity

cd tests
python test_ibeam_api.py

๐Ÿณ Docker Usage

Start IBeam Service

# Start IBeam container
docker-compose up -d

# Check logs
docker-compose logs -f ibeam

# Stop service
docker-compose down

IBeam Configuration

The docker-compose.yml configures IBeam with:

  • API Port: 5500 (mapped from container port 5000)
  • Health Check Port: 5501 (mapped from container port 5001)
  • Persistent Storage: ibeam_data volume for Gateway files
  • Environment Variables: Account credentials and trading mode

๐Ÿ“‹ API Reference

IDataProvider Interface

class IDataProvider(ABC):
    async def connect(self) -> bool
    async def disconnect(self) -> None
    async def get_account_info(self) -> Optional[AccountInfo]
    async def get_positions(self) -> List[Position]
    async def get_market_data(self, symbol: str) -> Optional[MarketData]

Data Models

Position

Position(
    symbol: str,           # Trading symbol
    quantity: float,       # Number of shares/contracts
    market_value: float,   # Current market value
    avg_cost: float,       # Average cost per share
    sec_type: str = 'STK', # Security type
    delta: float = 0.0,    # Option delta
    strike: Optional[float] = None,  # Strike price
    expiry: Optional[datetime] = None # Expiry date
)

AccountInfo

AccountInfo(
    account_id: str,         # Account identifier
    net_liquidation: float,  # Total account value
    total_cash: float = 0.0, # Available cash
    buying_power: float = 0.0 # Buying power
)

MarketData

MarketData(
    symbol: str,                    # Trading symbol
    last_price: float = 0.0,       # Last traded price
    bid: Optional[float] = None,    # Bid price
    ask: Optional[float] = None,    # Ask price
    timestamp: Optional[datetime] = None # Data timestamp
)

๐Ÿ” Troubleshooting

IBeam Connection Issues

  1. Check IBeam Status

    docker-compose ps
    docker-compose logs ibeam
    
  2. Verify Authentication

    curl -k https://localhost:5500/v1/api/iserver/auth/status
    
  3. Re-authenticate if needed

Common Issues

  • Port 5000 conflict: IBeam uses port 5500 to avoid macOS Control Center conflict
  • SSL Warnings: IBeam uses self-signed certificates (warnings are disabled in code)
  • Market Data N/A: Markets may be closed or data subscription required
  • TimeoutError: Check IBeam authentication status

๐Ÿ› ๏ธ Development

Project Structure

  • Data Providers: Abstract data access using the Strategy pattern
  • Business Logic: Pure functions for leverage calculations
  • Dependency Inversion: High-level modules don't depend on low-level details
  • Clean Architecture: Separation of concerns across layers

Adding New Data Providers

  1. Implement the IDataProvider interface
  2. Add to data_providers/__init__.py
  3. Create corresponding tests
  4. Update documentation

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • IBeam: For providing excellent Interactive Brokers API access
  • Interactive Brokers: For the Client Portal Web API
  • voyz/ibeam: For the containerized IBeam solution

Top categories

svelte logo

Need a Svelte website built?

Hire a professional Svelte developer today.
Loading Svelte Themes