A collection of quantitative finance models for investment analysis.* Mathematical methodology is documented in typeset/atemoya.pdf.
- Getting Started
- Technology Stack
- Configuration
- Models Overview
- Pricing & Risk
- Regime Downside
- Pairs Trading
- Liquidity Analysis
- Tail Risk Forecast
- Market Regime Forecast
- Dispersion Trading
- Gamma Scalping
- Volatility Arbitrage
- Variance Swaps
- Skew Trading
- Skew Verticals
- Options Hedging
- FX Hedging
- Earnings Vol Scanner
- Forward Factor Scanner
- Pre-Earnings Straddle
- Perpetual Futures
- Systematic Risk Signals
- Valuation
- Monitoring
Prerequisites: Docker and Docker Compose installed (Install Docker)
Interactive Menu (Recommended):
./docker-run.shQuick Workflow:
- Run
./docker-run.sh→ Choose 1) Build (first time only, ~5-10 min) - Choose 3) Start container
- Choose 5) Run quickstart menu → Navigate to your model
Or run directly with flags (no interactive menu):
./docker-run.sh build # Build image (first time)
./docker-run.sh up # Start container
./docker-run.sh exec # Run quickstart menu
./docker-run.sh shell # Open shell, then run ./quickstart.sh
./docker-run.sh down # Stop container
./docker-run.sh clean # Remove everythingWhat's included:
- OCaml environment (OPAM, Dune) pre-installed
- Python environment (uv, dependencies) pre-installed
- All models pre-built and tested
- Persistent outputs (saved to host)
- Multi-architecture support (ARM64 and x86_64)
- No local setup required
cd atemoya/
./quickstart.shThe interactive quickstart script guides you through installation, compilation, and running any model.
Build & Test All Models:
# Via Docker
docker compose exec atemoya bash -c 'eval $(opam env) && dune build @all && dune test'
# Native
dune build @all && dune testOCaml (Computation) — Core algorithms, optimizations, and LP formulations via Dune build system
Python (Data & Visualization) — Data fetching, linear programming (CVXPY), and plotting (matplotlib)
- Unified data fetcher with pluggable providers (
lib/python/data_fetcher/)- yfinance (default) - Free, no API key required
- IBKR - Interactive Brokers API (requires account)
- Additional data: FRED (macro), SEC EDGAR (filings), Google Trends, Discord (NLP sentiment)
LaTeX (Documentation) — Mathematical methodology writeup (typeset/). Requires pdflatex on host (not included in Docker).
Build & Tooling — Dune, OPAM, UV, Docker
Some features require configuration via environment variables. A template is provided:
# Copy the template
cp .env.example .env
# Edit with your values
nvim .env
# Load into current shell session
source .envAvailable settings:
| Variable | Purpose | Required? |
|---|---|---|
IBKR_* |
Interactive Brokers connection | Only if using IBKR data |
NTFY_TOPIC |
Push notification topic | Only if using watchlist alerts |
DATA_PROVIDER |
Data source (yfinance/ibkr) | No (defaults to yfinance) |
The .env file is gitignored and will never be committed. Most models work without any configuration using free yfinance data.
Atemoya contains 33+ quantitative models organized into four categories:
| Model | Question it answers | Output |
|---|---|---|
| Regime Downside | How to beat the benchmark with risk control? | Portfolio weights via LP |
| Pairs Trading | Are these two stocks cointegrated? | Spread signals + hedge ratios |
| Liquidity Analysis | Can I trade this without slippage? | Liquidity scores + volume signals |
| Tail Risk Forecast | What's my worst-case loss tomorrow? | VaR/ES at 95% and 99% |
| Dispersion Trading | Is index vol mispriced vs constituents? | Dispersion signals + Greeks |
| Gamma Scalping | Can I profit from delta-hedging? | Simulation P&L + Greeks |
| Volatility Arbitrage | Is IV too high or low vs realized? | Vol forecasts + signals |
| Variance Swaps | How to trade variance directly? | Swap pricing + Greeks |
| Skew Trading | Is the volatility smile mispriced? | Skew metrics + signals |
| Skew Verticals | Which vertical spreads have edge? | Edge scores + spreads |
| Options Hedging | How to protect my portfolio cheaply? | Pareto-optimal hedges |
| FX Hedging | How to manage currency exposure? | Hedge ratios + costs |
| Earnings Vol Scanner | Will IV crush after earnings? | Calendar/straddle signals |
| Forward Factor Scanner | Is the term structure in backwardation? | Calendar spread signals |
| Pre-Earnings Straddle | Should I buy a straddle before earnings? | Predicted returns + sizing |
| Perpetual Futures | Is funding rate mispriced? | Basis + funding signals |
| Market Regime Forecast | What regime are we in? | HMM state probabilities |
| Systematic Risk Signals | Is correlation compressing? | Risk regime + transition probability |
| Model | Question it answers | Output |
|---|---|---|
| DCF Deterministic | What is the intrinsic value? | IVPS via FCFE/FCFF + sensitivity |
| DCF Probabilistic | What's the distribution of fair value? | Monte Carlo IVPS + efficient frontiers |
| DCF REIT | What is a REIT worth? | FFO/NAV/DDM fair value + quality |
| Normalized Multiples | Cheap or expensive vs sector? | Percentile ranks + implied prices |
| Relative Valuation | Cheap or expensive vs peers? | Implied price from peer multiples |
| GARP / PEG Analysis | Is growth priced fairly? | PEG ratio + composite score |
| Growth Analysis | How fast and how sustainable? | Growth score + Rule of 40 |
| Dividend / Income | Is the dividend safe and growing? | Safety score + DDM value |
| Crypto Treasury | Is the BTC premium justified? | mNAV + implied BTC price |
| ETF Analysis | Is the ETF well-structured? | Expense + tracking + type analysis |
| Analyst Upside | Where do analysts see upside? | Upside ranking + conviction map |
| Tool | What it does | Output |
|---|---|---|
| Watchlist & Alerts | Track tickers for price/signal alerts | Push notifications via ntfy.sh |
| Earnings Calendar | When do my holdings report? | Earnings timeline + EPS surprise |
What are you trying to do?
│
├─ Build or size a portfolio ──────────────── What approach?
│ ├─ Regime-aware optimization .............. Regime Downside
│ └─ Statistical arbitrage .................. Pairs Trading
│
├─ Trade volatility ──────────────────────── Which strategy?
│ ├─ IV vs RV ............................... Volatility Arbitrage
│ ├─ Index vs constituents .................. Dispersion Trading
│ ├─ Smile shape ............................ Skew Trading / Skew Verticals
│ ├─ Variance exposure ...................... Variance Swaps
│ ├─ Delta-neutral gamma .................... Gamma Scalping
│ └─ Crypto perpetuals ...................... Perpetual Futures
│
├─ Hedge ─────────────────────────────────── What exposure?
│ ├─ Equity portfolio ....................... Options Hedging
│ └─ Currency ............................... FX Hedging
│
├─ Measure risk ──────────────────────────── What horizon?
│ ├─ Next-day tail risk ..................... Tail Risk Forecast
│ ├─ Liquidity / tradability ................ Liquidity Analysis
│ ├─ Regime detection ....................... Market Regime Forecast
│ └─ Systematic risk / correlation regime ... Systematic Risk Signals
│
├─ Screen for opportunities ──────────────── What kind?
│ ├─ Earnings volatility plays .............. Earnings Vol / Pre-Earnings Straddle
│ ├─ Term structure backwardation ........... Forward Factor Scanner
│ ├─ Analyst consensus upside ............... Analyst Upside
│ └─ Growth quality ......................... Growth Analysis
│
├─ Value a stock ─────────────────────────── Which kind?
│ ├─ General equity ......................... DCF Deterministic / Probabilistic
│ ├─ Compare to sector/peers ................ Normalized Multiples / Relative Valuation
│ ├─ Growth at a reasonable price ........... GARP PEG
│ ├─ Income / dividends ..................... Dividend Income
│ ├─ REIT ................................... DCF REIT
│ ├─ BTC treasury company ................... Crypto Treasury
│ └─ ETF .................................... ETF Analysis
│
├─ Monitor ───────────────────────────────── What signal?
│ ├─ Price / technical alerts ............... Watchlist & Alerts
│ └─ Earnings dates / EPS surprises ......... Earnings Calendar
│
Portfolio Optimization | Benchmark-Relative
Beat the S&P 500 while controlling downside and tail risk through regime-aware optimization.
Key Features:
- Minimizes persistent underperformance (LPM1) and tail risk (CVaR)
- Detects volatility regimes, compresses beta in stress (target: 0.65)
- Trades infrequently (~30% annual turnover) with transaction cost penalties
- Spec-compliant LP solver (CVXPY) with weekly scenarios
Documentation: pricing/regime_downside/README.md
Interpreting Results:
- Portfolio Weights: Rebalance to these allocations when the model triggers; cash allocation increases in stress regimes
- Rebalance Trigger: Only trade when "Improvement" exceeds threshold - avoids churning
- Beta < 0.65: Defensive positioning; model expects volatility - reduce equity exposure
- Beta > 0.65: Aggressive positioning; model sees opportunity - increase equity exposure
- Gap Analysis: Large gap between frictionless/constrained = turnover constraints are binding; small gap = optimal portfolio is achievable
Example Output:
Portfolio Weights Over Time:
Risk Metrics:
Gap Analysis (Frictionless vs Constrained):
Statistical Arbitrage | Cointegration
Market-neutral profits from mean reversion in cointegrated asset pairs.
Key Features:
- Engle-Granger cointegration testing
- Augmented Dickey-Fuller (ADF) test with optimal lag selection
- OLS hedge ratio estimation
- Mean reversion half-life calculation
- Spread z-score signals for entry/exit
Interpreting Results:
- Cointegrated = YES: Pair is tradeable; spread is mean-reverting
- Cointegrated = NO: Avoid this pair - no statistical edge
- Z-Score > +2: SHORT spread (sell Y, buy X) - spread is extended high
- Z-Score < -2: LONG spread (buy Y, sell X) - spread is extended low
- |Z-Score| < 0.5: EXIT position - spread has reverted to mean
- Half-Life: Expected holding period; shorter = faster mean reversion = better
Example Output:
Documentation: pricing/pairs_trading/README.md
Liquidity Scoring & Predictive Signals
Score stocks by tradability and generate volume-based predictive signals.
Key Features:
- Liquidity scoring (0-100) with tier classification (Excellent/Good/Fair/Poor)
- Amihud illiquidity ratio, turnover ratio, relative volume
- On-Balance Volume (OBV) with divergence detection
- Volume surge detection and trend analysis
- Accumulation/Distribution signals
- Smart money flow estimation
- Volume-price confirmation analysis
Interpreting Results:
- Liquidity Score > 70: Excellent/Good - easy to trade, tight spreads
- Liquidity Score < 50: Poor - wider spreads, higher market impact
- Relative Volume > 2x: Volume surge - potential breakout/breakdown
- OBV Divergence: Price and volume moving opposite - potential reversal
- Bullish Signal: Volume confirms price move up
- Bearish Signal: Volume confirms price move down
Example Output:
Liquidity Dashboard (Multi-Ticker):
VaR/ES Forecasting | HAR-RV Model
Forecast next-day Value-at-Risk and Expected Shortfall using realized variance from intraday returns.
Key Features:
- Realized Variance (RV): Computed from 5-minute intraday returns (sum of squared returns)
- HAR-RV Model: Heterogeneous Autoregressive model with daily/weekly/monthly lookbacks
- Jump Detection: Threshold-based variance jumps (2.5 std devs above rolling mean)
- Tail Risk: VaR (95%/99%) and Expected Shortfall using t(6) distribution for fat tails
Data Sources:
- IBKR (preferred): Up to 1 year of 5-minute data with market data subscription
- yfinance (fallback): Limited to 60 days of 5-minute data
SPY — Low Risk:
SOXL (3x Semiconductors) — High Risk:
Regime Detection | Covered Call Timing
Identify market regimes (trend + volatility state) and generate recommendations for income ETF strategies like covered calls.
Key Features:
- Four modeling approaches: Basic (GARCH+HMM), MS-GARCH, BOCPD (Bayesian changepoint), Gaussian Process
- Trend detection: Bull / Bear / Sideways classification via Hidden Markov Models
- Volatility regime: High / Normal / Low based on historical percentiles
- Covered call suitability: 1-5 star rating based on regime combination
- Income ETF mapping: SPY→JEPI/XYLD, QQQ→JEPQ/QYLD, single stocks→YieldMax ETFs
- Earnings calendar: Flags tickers within 7-14 days of earnings as elevated risk
Volatility Arbitrage | Correlation Trading
Exploit differences between index implied volatility and constituent volatilities.
Key Features:
- Implied correlation extraction from volatility surfaces
- Dispersion level and z-score calculation
- Long/short dispersion trade construction
- Portfolio Greeks aggregation (delta, gamma, vega, theta)
- P&L attribution to correlation convergence
Interpreting Results:
- Implied Correlation > 0.7: Index vol is rich vs constituents - SELL index vol, BUY single-name vol
- Implied Correlation < 0.5: Index vol is cheap - BUY index vol, SELL single-name vol
- Dispersion Z-Score > 2: Strong signal to trade dispersion
- Vega P&L: Shows profit/loss from correlation convergence
- Net Delta: Should be near zero for market-neutral position
Example Output:
Options Trading | Delta-Neutral Gamma
Profit from realized volatility through delta-hedged option positions.
Key Features:
- Black-Scholes Greeks calculation
- Straddle/strangle position construction
- Delta-hedging simulation with rebalancing
- P&L decomposition (gamma, theta, vega)
- Hedging frequency optimization
Interpreting Results:
- Gamma P&L > 0: Realized vol exceeded implied - strategy profitable from hedging gains
- Theta P&L: Always negative - cost of holding options; must be offset by gamma gains
- Net P&L: Gamma P&L + Theta P&L; positive = RV > IV, negative = IV > RV
- Rehedge Frequency: More frequent = smoother P&L but higher transaction costs
- Entry Signal: Buy straddle when IV is low relative to expected RV
Example Output:
P&L Attribution:
Summary Metrics:
Documentation: pricing/gamma_scalping/README.md
Volatility Trading | IV vs RV
Identify and trade implied vs realized volatility divergences.
Key Features:
- Realized volatility estimation (close-to-close, Parkinson, etc.)
- IV/RV ratio analysis
- Volatility forecasting models
- Mean reversion signals
- Position recommendations
Interpreting Results:
- IV/RV Ratio > 1.2: IV is rich - SELL volatility (sell straddles, sell variance)
- IV/RV Ratio < 0.8: IV is cheap - BUY volatility (buy straddles, buy variance)
- RV Forecast: Expected future realized vol; compare to current IV for edge
- Vol of Vol: High vol-of-vol = uncertain forecast, reduce position size
- Mean Reversion Signal: IV tends to revert to RV over time
Example Output:
Documentation: pricing/volatility_arbitrage/README.md
Derivatives | VRP Harvesting
Price variance swaps via Carr-Madan replication and harvest the variance risk premium — the persistent gap between implied and realized variance.
Key Features:
- Carr-Madan variance swap pricing (1/K² weighted OTM options)
- 5 realized variance estimators (Close-to-Close, Parkinson, Garman-Klass, Rogers-Satchell, Yang-Zhang)
- 3 forecast models (Historical RV, EWMA, GARCH(1,1))
- VRP signal generation with confidence scoring and Kelly sizing
- Options replication portfolio with delta/vega/gamma Greeks
Documentation: pricing/variance_swaps/README.md
Interpreting Results:
- VRP% > +2%: Implied variance exceeds forecast — SHORT variance to harvest premium
- VRP% < -1%: Rare; realized exceeds implied — LONG variance for mean reversion
- Confidence: Scales linearly from threshold to cap; drives position sizing
- Vega Notional: P&L sensitivity per 1% vol move = Notional / (2·√K_var)
Example Output (Close-to-Close + Historical — baseline):
Variance Risk Premium:
Trading Signal:
With Yang-Zhang + GARCH(1,1) — recommended:
Variance Risk Premium:
Trading Signal:
Volatility Surface | Smile Arbitrage
Trade the shape of the volatility smile/skew.
Key Features:
- Put/call skew measurement
- Skew z-score for mean reversion signals
- Risk reversal and butterfly construction
- Skew term structure analysis
- Historical skew percentiles
Interpreting Results:
- Skew Z-Score > 2: Put skew is steep (expensive) - SELL risk reversals (sell puts, buy calls)
- Skew Z-Score < -2: Put skew is flat (cheap) - BUY risk reversals (buy puts, sell calls)
- Term Structure Slope: Upward = contango (normal); Inverted = backwardation (fear)
- Vol Smile Shape: Steeper left side = crash protection is expensive
- ATM Vol Level: Context for skew trades; high ATM vol = elevated fear overall
Example Output:
Volatility Smile:
Skew Time Series:
Backtest P&L:
Documentation: pricing/skew_trading/README.md
Options Spreads | Skew Mean Reversion
Vertical spreads that profit from volatility skew normalization.
Key Features:
- Normalized call/put skew metrics
- Skew z-score calculation
- Bull call and bear put spread construction
- Multi-factor edge scoring (0-100)
- Probability of profit estimation
Interpreting Results:
- Edge Score > 70: High conviction trade - skew is significantly mispriced
- Edge Score 50-70: Moderate conviction - consider smaller position
- Edge Score < 50: Low edge - pass or wait for better setup
- Bull Call Spread: Recommended when call skew is flat (OTM calls cheap)
- Bear Put Spread: Recommended when put skew is steep (OTM puts expensive)
- Probability of Profit: Higher = more likely to profit but lower max gain
Dashboard:
Risk Management | Portfolio Protection
Optimize equity portfolio hedges using options strategies with multi-objective optimization.
Key Features:
- Dual vol surface models (SVI + SABR) calibrated from market option chains
- Four strategies: protective put, collar, vertical spread, covered call
- Pareto frontier optimization (cost vs protection)
- Dual pricing: Black-Scholes (analytical) + Monte Carlo (Longstaff-Schwartz)
- Complete Greeks: Delta, Gamma, Vega, Theta, Rho
Documentation: pricing/options_hedging/README.md
Interpreting Results:
- Pareto Frontier: Points on the curve are optimal cost/protection tradeoffs; choose based on budget
- Lower-Left: Cheap but less protection (e.g., OTM puts)
- Upper-Right: Expensive but full protection (e.g., ATM puts)
- Dominated Points: Below the curve = inefficient; better alternatives exist
- Strategy Selection: Collars reduce cost but cap upside; put spreads limit max payout
Example Output:
SVI Implied Volatility Surface (3D + Smile Overlay):
SABR Implied Volatility Surface (3D + Smile Overlay):
Pareto Frontier (Cost vs Protection):
Strategy Payoffs:
Greeks Summary:
Currency Risk | International Portfolios
Manage foreign exchange exposure for international investments.
Key Features:
- Covered interest rate parity (forward pricing)
- Black-76 model for FX options
- Optimal hedge ratio calculation
- Cost-benefit analysis of hedging strategies
- Multi-currency portfolio support
Documentation: pricing/fx_hedging/README.md
Interpreting Results:
- Hedge Ratio: Percentage of FX exposure to hedge (0-100%); 100% = fully hedged
- Forward Points: Cost/benefit of forward hedge vs spot; negative = hedging costs money
- Optimal Hedge: Balance between hedging cost and volatility reduction
- Unhedged VaR: Maximum expected loss from currency moves
- Hedged VaR: Reduced risk after implementing hedge
Example Output:
Exposure Analysis (CHF investor, USD equities + crypto):
Hedge Performance — CHF/USD (USD equity exposure):
Hedge Performance — Ether (crypto exposure):
Event Trading | IV Term Structure
Identify profitable volatility trades around earnings announcements.
Key Features:
- IV term structure slope and ratio analysis
- IV/RV comparison for richness detection
- Expected move calculation
- Kelly criterion position sizing
- Calendar spread and straddle recommendations
Interpreting Results:
- IV Ratio (Front/Back) > 1.5: Front-month IV elevated for earnings - SELL calendar spreads
- IV Ratio < 1.2: Front-month IV cheap - BUY calendars or straddles
- Expected Move: Market-implied earnings move; compare to historical for edge
- IV Crush Signal: High pre-earnings IV will collapse post-announcement
- Straddle Recommendation: BUY if expected move > straddle cost; SELL if overpriced
Sample Output:
Term Structure | Calendar Spreads
Detect backwardation in volatility term structure for calendar spread opportunities.
Key Features:
- Forward volatility calculation from variance decomposition
- Forward factor (backwardation strength) measurement
- ATM and double calendar spread construction
- Position sizing scaled by forward factor magnitude
- Multi-ticker, multi-DTE scanning
Interpreting Results:
- Forward Factor > 1: Backwardation - near-term IV higher than forward IV; SELL calendars
- Forward Factor < 1: Contango (normal) - forward IV higher; BUY calendars
- Forward Factor << 0.8: Strong contango signal - high conviction calendar buy
- Position Size: Scale by forward factor magnitude; larger deviation = larger position
- Double Calendar: Use when both calls and puts show similar signal
Sample Output:
ML-Based | Earnings Prediction
Machine learning model to predict profitable pre-earnings straddle trades.
Key Features:
- 4-signal linear regression model
- IV ratio and IV-RV gap signals
- Predicted return and Kelly sizing
- Recommendation thresholds (Strong Buy, Buy, Pass)
- Historical backtest statistics
Interpreting Results:
- Predicted Return > 10%: Strong Buy - model expects profitable straddle
- Predicted Return 5-10%: Buy - moderate expected profit
- Predicted Return < 5%: Pass - insufficient edge after costs
- Kelly Fraction: Recommended position size as % of capital
- Signal Breakdown: Check which factors (IV ratio, IV-RV gap) are driving the signal
Dashboard:
Crypto Derivatives | No-Arbitrage Pricing
Price perpetual futures contracts and everlasting options using closed-form solutions from Ackerer, Hugonnier & Jermann (2025).
Key Features:
- Three contract types: Linear (USD-margined), Inverse (BTC-margined), Quanto (cross-currency)
- Everlasting options: Perpetual calls/puts with closed-form pricing and Greeks
- Real-time data: Binance, Deribit, Bybit exchange integration
- Arbitrage detection: Compare theoretical vs market prices for trading signals
- Funding rate analysis: Fair funding rate calculation and basis tracking
Early-warning framework for detecting systematic risk in financial markets, based on graph theory (minimum spanning tree) and covariance matrix eigenvalue analysis. See full documentation.
Equity Valuation | Traditional DCF
Deterministic discounted cash flow valuation using FCFE and FCFF methods.
Key Features:
- Dual valuation: Free Cash Flow to Equity (FCFE) and Free Cash Flow to Firm (FCFF)
- 9-category investment signals (Strong Buy → Avoid/Sell)
- CAPM cost of equity, WACC with leveraged beta (Hamada formula)
- Implied growth solver (what growth is the market pricing in?)
- Sensitivity analysis (growth, discount rate, terminal growth)
- Multi-country support (20+ countries with RFR, ERP, tax rates)
Documentation: valuation/dcf_deterministic/README.md
Interpreting Results:
- Margin of Safety > 30%: Strong buy candidate - intrinsic value significantly exceeds market price
- Margin of Safety 10-30%: Moderate buy - some upside but less conviction
- Margin of Safety < 10%: Fairly valued - no clear edge
- Negative Margin: Overvalued - avoid or consider shorting
- Implied Growth: If market-implied growth exceeds 15%, the stock may be priced for perfection
- Sensitivity Heatmap: Green regions show parameter combinations where stock remains undervalued
Example Output:
Valuation Comparison (Standard Companies):
Bank Valuation Comparison (Excess Returns Model):
Insurance Valuation Comparison (Embedded Value Model):
Oil & Gas E&P Valuation Comparison (NAV Model):
Sensitivity Analysis — Standard DCF (Growth Rate, Discount Rate, Terminal Growth):
Sensitivity Analysis — Bank (ROE, Cost of Equity, Sustainable Growth):
Sensitivity Analysis — Insurance (Combined Ratio, Investment Yield, Cost of Equity):
Sensitivity Analysis — Oil & Gas (Oil Price, Lifting Cost, Discount Rate):
Equity Valuation | Monte Carlo Simulation
Advanced DCF with Monte Carlo simulation for uncertainty quantification.
Key Features:
- Monte Carlo simulation (100-10,000 iterations)
- Stochastic discount rates (samples RFR, beta, ERP each iteration)
- Time-varying growth rates (exponential mean reversion)
- Bayesian priors for ROE/ROIC smoothing
- Portfolio efficient frontier (multi-asset optimization)
- Distribution statistics (mean, median, percentiles, probability of undervaluation)
Documentation: valuation/dcf_probabilistic/README.md
Interpreting Results:
- P(Undervalued) > 70%: High-conviction buy - most simulation paths show upside
- P(Undervalued) 50-70%: Moderate conviction - coin flip with slight edge
- P(Undervalued) < 50%: More likely overvalued - avoid or reduce position
- KDE Plot: Vertical line shows market price; area to the right = probability of undervaluation
- Surplus Distribution: Positive surplus = undervalued; check the median and 5th percentile for downside
- Efficient Frontier: Points on the curve are optimal; choose based on your risk tolerance (left = conservative, right = aggressive)
Example Output:
Standard Model — Intrinsic Value Distribution (KDE):
Standard Model — Surplus Distribution:
Bank (Excess Return Model) — Fair Value Distribution:
Insurance (Float-Based Model) — Fair Value Distribution:
Oil & Gas (NAV Model) — Fair Value Distribution:
Portfolio Efficient Frontiers (6 risk measures, FCFF top / FCFE bottom):
μ–σ (Sharpe Ratio):
μ–P(Loss) (Tail Risk):
μ–σ↓ (Sortino / Downside Deviation):
μ–CVaR (Conditional Value-at-Risk):
μ–VaR (Value-at-Risk):
μ–Max Drawdown (Calmar Ratio):
REIT Valuation | FFO/AFFO, NAV, DDM
Specialized valuation model for Real Estate Investment Trusts using industry-standard metrics.
Key Features:
- FFO/AFFO calculations (Funds From Operations adjusted for maintenance CapEx)
- NAV valuation (Net Asset Value from NOI/cap rate)
- Dividend Discount Model (Gordon Growth, two-stage DDM)
- P/FFO and P/AFFO relative valuation vs sector benchmarks
- Quality scoring (occupancy, lease quality, balance sheet, growth, dividend safety)
- 11 property sectors with sector-specific cap rates and multiples
Documentation: valuation/dcf_reit/README.md
Interpreting Results:
- Upside > 15%: Undervalued REIT - consider buying
- NAV Premium/Discount: Trading above NAV = expensive; below NAV = potential value
- AFFO Payout > 100%: Dividend may be unsustainable - caution
- Quality Score > 0.7: High-quality REIT deserves premium valuation
- Quality Score < 0.5: Elevated risk - requires larger margin of safety
- P/FFO vs Sector: Below sector average with high quality = attractive entry
Example Output:
Industrial REIT — PLD (Hold, Quality 0.86):
Net Lease REIT — O (Sell, Quality 0.72):
Data Center REIT — EQIX (Strong Sell, Quality 0.64):
Mortgage REIT — STWD (Caution, Quality 0.38):
Crypto Treasury Valuation | mNAV Model
Valuates companies holding Bitcoin and/or Ethereum as treasury assets using the multiple of Net Asset Value (mNAV) methodology.
Key Features:
- Real-time BTC and ETH prices from yfinance (BTC-USD, ETH-USD)
- mNAV calculation (Market Cap / Crypto Holdings Value)
- Support for pure BTC, pure ETH, and mixed holdings
- Premium/discount analysis
- Implied crypto price (what market values BTC/ETH at via the stock)
- Cost basis tracking and unrealized gains
- Leverage analysis (Debt/NAV)
Interpreting Results:
- mNAV < 0.8: Deep discount - strong buy (getting BTC below spot)
- mNAV 0.8-1.0: Moderate discount - buy
- mNAV 1.0-1.2: Fair to slight premium - hold
- mNAV > 1.5: Significant premium - consider buying BTC directly
- Implied BTC Price: Compare to spot - lower = undervalued
Example Output:
Crypto Treasury Comparison (BTC and ETH Plays):
Growth At a Reasonable Price | PEG Ratio
Combines value and growth investing—growth is worth paying for, but not at any price.
Key Features:
- PEG ratio calculation (Trailing, Forward, PEGY variants)
- GARP scoring system (0-100) with component breakdown
- Quality assessment (FCF conversion, D/E ratio, ROE)
- Investment signals (Strong Buy → Avoid)
- Multi-ticker comparison and ranking
Interpretation:
- PEG < 0.5: Very Undervalued
- PEG 0.5-1.0: Undervalued
- PEG 1.0-1.5: Fairly valued
- PEG > 2.0: Expensive for growth rate
Example Output:
Strong Buy — META (85/A, PEG 0.44):
Buy — SFM (70/B, PEG 1.04):
Hold — AAPL (60/B, PEG 1.65):
Avoid — PLTR (67/B, PEG 2.87):
Avoid — COST (60/B, PEG 2.24):
Multi-Ticker Comparison:
Pure Growth Investing | Growth Metrics
Evaluate companies on growth potential, accepting higher valuations for exceptional growth.
Key Metrics:
- Revenue CAGR: Compound annual growth rate (Hypergrowth > 40%, High > 20%)
- Rule of 40: Revenue Growth % + FCF Margin % (> 40 = excellent)
- Operating Leverage: Earnings growth / Revenue growth
- PEG Ratio: P/E divided by earnings growth rate
Growth Quality Assessment:
- Margin trajectory (Expanding, Stable, Contracting)
- Operating leverage (earnings growing faster than revenue)
- EV/Revenue per point of growth
Example Output:
Hypergrowth — PLTR (91/A, Growth Buy):
Hypergrowth — NVDA (89/A, Strong Growth):
High Growth — CRWD (43/C, Growth Hold):
Moderate Growth — SFM (50/C+, Growth Hold):
Slow Growth — JNJ (49/C+, Not a Growth Stock):
Multi-Ticker Comparison:
Dividend Investing | Income Generation
Evaluate stocks for dividend yield, safety, and growth—answers "How much income will it pay?"
Key Metrics:
- Dividend Yield: Annual dividend / Price (2-5% typical target)
- Payout Ratio: Dividends / Earnings or FCF (<70% = sustainable)
- Dividend Growth Rate (DGR): CAGR of dividend increases
- Consecutive Increases: Aristocrat (25+ years), King (50+ years)
- Chowder Number: Yield + 5-year DGR (>12 for high yield, >15 for low yield)
Dividend Safety Scoring:
- Payout ratio sustainability
- FCF coverage of dividends
- Balance sheet strength
- Earnings stability
- Track record of increases
Valuation Methods:
- Gordon Growth Model (DDM): D1 / (r - g)
- Two-Stage DDM for transitioning companies
- Yield-based valuation vs historical average
Use Cases:
- Build income-generating portfolios
- Screen for dividend safety before purchase
- Monitor existing holdings for cut risk
- Compare yield vs peers
Default Comparison: JNJ, KO, PEP, PG, VZ, MO — classic dividend aristocrats and kings.
Note: For REITs, use the dcf_reit model which handles FFO/AFFO metrics. Streak detection handles yfinance split-adjustment artifacts automatically.
Comparable Company Analysis | Peer Multiples
Value stocks relative to peers using multiples—answers "Is it cheap vs similar companies?"
Key Multiples:
- Equity: P/E, P/B, P/S, P/FCF
- Enterprise Value: EV/EBITDA, EV/EBIT, EV/Revenue
- Sector-Specific: P/FFO (REITs), EV/ARR (SaaS), P/TBV (Banks)
Sector-Benchmarked Valuation | Quality-Adjusted Percentiles
Evaluate stocks by comparing their multiples (P/E, EV/EBITDA, P/S, etc.) against sector benchmarks with quality adjustments for growth, margins, and returns.
Note: This module is designed for general sectors (technology, consumer, industrials, healthcare, etc.). It is not suitable for financials (banks, insurance) or resource sectors (oil & gas), which require specialized metrics — see DCF Deterministic for sector-specific models.
Key Features:
- TTM + NTM multiples — trailing and forward views
- Percentile ranking vs sector P25/median/P75
- Quality adjustment — superior fundamentals justify premium multiples
- Implied prices from each multiple method
- Single and comparative analysis modes
CAT (Fair Value, 71% conf.):
DE (Fair Value, 69% conf.):
GE (Overvalued, 51% conf.):
HON (Fair Value, 77% conf.):
Comparative Analysis — CAT, DE, GE, HON:
Analyst Price Target Scanner | Conviction Mapping
Scan stocks for analyst price target upside, rank by opportunity size, and map conviction (high upside + low dispersion = strongest signal). Analyst consensus data is sourced from Yahoo Finance (via yfinance), which aggregates sell-side estimates from major brokerages through Refinitiv/LSEG.
Key Features:
- 15 predefined universes — index (S&P 500, NASDAQ, Dow), sector (tech, healthcare, industrials, consumer, financials, energy), thematic (AI, clean energy, dividend aristocrats), market-cap (mid-cap, small-cap), or custom tickers
- Parallel fetching — concurrent data retrieval via yfinance
- Dispersion analysis — measures analyst disagreement (high-low range / mean)
- 52-week positioning — where the stock sits relative to its range
- Sector breakdown — average upside by sector
Metrics per stock:
- Current price vs median/mean target
- Upside % and analyst count
- Dispersion (analyst disagreement)
- Recommendation consensus (strong buy → sell)
ETF Valuation & Quality Scoring
Comprehensive ETF analysis covering premium/discount, tracking quality, costs, liquidity, and specialized derivatives-based ETF strategies.
Standard ETF Metrics:
- Premium/Discount: Price vs NAV gap (arbitrage opportunities)
- Tracking Error: How well ETF follows its benchmark
- Total Cost of Ownership: Expense ratio + trading costs + tax costs
- Liquidity Score: Spread, volume, implied liquidity from holdings
- Size Tier: AUM-based stability assessment
Derivatives-Based ETF Analysis:
| Type | Examples | Key Metrics |
|---|---|---|
| Covered Call | JEPI, QYLD, XYLD | Upside capture, distribution yield, capture efficiency |
| Buffer/Outcome | BAPR, PJAN | Remaining buffer, remaining cap, days to outcome |
| Volatility | VXX, UVXY | Contango/backwardation, roll yield, decay rate |
| Put-Write | PUTW | Premium yield, assignment risk |
Default Comparison: SPY, QQQ, JEPI, SCHD — index trackers vs income ETFs.
Covered Call ETF — JEPI (80/B+):
Standard Index ETF — SPY (75/B+):
Portfolio Tracking with Weighted Thesis Scoring
Track positions (long, short, watching) with weighted bull/bear thesis arguments. OCaml analysis engine scores conviction, calculates P&L, and generates alerts for price targets, stop losses, and significant gains/losses. Push notifications via ntfy.sh.
Features:
- Weighted bull/bear thesis scoring with conviction levels (strong bull → strong bear)
- Position types: long, short, watching — with correct P&L and alert direction for each
- Price alerts: buy targets, sell targets, stop losses (direction-aware for shorts)
- P&L alerts: significant gains (>20%) and losses (>10%) from cost basis
- ntfy.sh integration for push notifications
- State tracking for change detection between runs
Upcoming Earnings Tracking | Pre-Earnings Alerts | BMO/AMC Timing
Track upcoming earnings dates for portfolio holdings and generate alerts before earnings. Fetches data from yfinance with parallel processing.
Features:
- Upcoming earnings dates with BMO/AMC pre-/post-market timing
- Configurable alert window (default 14 days) with priority levels
- Historical EPS surprise tracking (last 4 quarters)
- Read tickers from watchlist portfolio.json or CLI
- ntfy.sh notification integration
Disclaimer. Nothing in this repository constitutes financial advice, investment advice, trading advice, or any recommendation to buy, sell, or hold any security. All model outputs are the product of simplified mathematical assumptions applied to noisy, incomplete data. Markets are non-ergodic systems: past distributions do not reliably describe future outcomes, ensemble averages do not converge to time averages for individual participants, and tail events reshape the landscape in ways no backtest captures. Every model here is wrong — some may occasionally be useful, but none should be mistaken for a forecast. Use at your own risk and consult a qualified financial professional before making any investment decision.