A clean, modular Python application for calculating portfolio leverage and implied financing rates using Interactive Brokers data via IBeam's Client Portal Web API.
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
The calculator uses the following formulas:
T = (expiry_date - today) / 365.25 # Years to expiration (precise)
E = delta * S * contracts * 100 # For options (100 shares per contract)
E = quantity * current_price # For stocks
Portfolio Leverage = Total Exposure / Net Liquidation Value
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.
Based on put-call parity with dividend adjustments, the calculator implements two primary methods:
# 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)
# 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)
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 |
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!)
The calculator assigns confidence levels based on option characteristics:
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.
Clone the repository
git clone <repository-url>
cd options
Install Python dependencies
pip install -r requirements.txt
# Or install as a package
pip install -e .
Set up environment variables
# Create .env file
IBKR_USERNAME=your_username
IBKR_PASSWORD=your_password
IBKR_TRADING_MODE=live # or 'paper'
Start IBeam
docker-compose up -d
Authenticate with IBeam
# 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
# 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
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())
cd tests
python test_leverage.py
cd tests
python test_ibeam_integration.py
cd tests
python test_ibeam_api.py
# Start IBeam container
docker-compose up -d
# Check logs
docker-compose logs -f ibeam
# Stop service
docker-compose down
The docker-compose.yml
configures IBeam with:
ibeam_data
volume for Gateway filesclass 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]
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
)
Check IBeam Status
docker-compose ps
docker-compose logs ibeam
Verify Authentication
curl -k https://localhost:5500/v1/api/iserver/auth/status
Re-authenticate if needed
IDataProvider
interfacedata_providers/__init__.py
This project is licensed under the MIT License - see the LICENSE file for details.