
Fixed Income
- 195 installs
- 257 repo stars
- Updated June 24, 2026
- agiprolabs/claude-trading-skills
fixed-income is a Claude Code skill that computes bond price, yield-to-maturity, duration, and convexity and outlines DeFi lending-rate analysis.
About
fixed-income is a stub skill that provides a working bond calculator for price, yield-to-maturity, duration, and convexity, plus an overview of planned bond and DeFi lending-rate analysis. A developer uses it to analyze bond mathematics and map it to variable-rate DeFi lending protocols on Solana. Full implementation is awaiting community contribution.
- STUB skill: working bond calculator (price, YTM, duration, convexity) plus planned roadmap
- Bridges traditional bond math to DeFi lending-rate modeling on Solana (Marginfi, Kamino, Solend)
- Informational and analytical only, not financial advice
Fixed Income by the numbers
- 195 all-time installs (skills.sh)
- Ranked #477 of 1,106 Finance & Trading skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
fixed-income capabilities & compatibility
- Capabilities
- yield analysis · data analysis
- Use cases
- data analysis · research · trading
What fixed-income says it does
Fixed income analysis bridges traditional bond mathematics with DeFi lending rate modeling.
This skill is informational and analytical only. It does not provide financial advice or trading recommendations.
npx skills add https://github.com/agiprolabs/claude-trading-skills --skill fixed-incomeAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 195 |
|---|---|
| repo stars | ★ 257 |
| Last updated | June 24, 2026 |
| Repository | agiprolabs/claude-trading-skills ↗ |
What it does
Compute bond price, yield, duration, and convexity and relate them to DeFi lending rates.
Who is it for?
Basic bond math (price, YTM, duration, convexity) and framing DeFi lending-rate comparison.
Skip if: Production yield-curve construction (planned, not implemented) or financial advice.
When should I use this skill?
You need bond pricing math or want to reason about DeFi lending term structure.
By the numbers
- 1 working bond calculator script
- 5 lending protocols tabulated
Files
Fixed Income
Status: STUB — This skill provides a basic bond calculator and an overview of planned capabilities. Full implementation is awaiting community contribution.
Fixed income analysis bridges traditional bond mathematics with DeFi lending rate modeling. Bond pricing fundamentals — present value of cash flows, yield curves, duration, and convexity — translate directly to analyzing DeFi lending protocols where depositors earn variable or fixed rates on crypto assets.
On Solana, lending protocols like Marginfi, Kamino, and Solend offer variable-rate lending/borrowing. Understanding term structure and rate dynamics helps optimize yield farming strategies and compare opportunities across protocols.
This skill is informational and analytical only. It does not provide financial advice or trading recommendations.
---
Current Capabilities
This stub includes a working bond calculator with price, yield-to-maturity, duration, and convexity computations. See scripts/bond_calculator.py for the implementation.
def bond_price(
face: float, coupon_rate: float, ytm: float, periods: int, freq: int = 2
) -> float:
"""Calculate bond price as present value of all cash flows.
Args:
face: Face (par) value of the bond.
coupon_rate: Annual coupon rate (decimal, e.g., 0.05 for 5%).
ytm: Yield to maturity (annual, decimal).
periods: Number of coupon periods remaining.
freq: Coupon frequency per year (2 = semi-annual).
Returns:
Bond price (dirty price).
"""
coupon = face * coupon_rate / freq
y = ytm / freq
pv_coupons = sum(coupon / (1 + y) ** t for t in range(1, periods + 1))
pv_face = face / (1 + y) ** periods
return pv_coupons + pv_faceRun the demo:
python scripts/bond_calculator.py --demo---
Planned Capabilities
When fully implemented, this skill will cover:
Bond Pricing
| Concept | Description |
|---|---|
| Clean/Dirty Price | Price excluding/including accrued interest |
| Accrued Interest | Interest earned since last coupon date |
| Day Count Conventions | 30/360, ACT/360, ACT/365, ACT/ACT |
| Zero-Coupon Bonds | Discount bonds with no periodic coupons |
Yield Measures
| Yield Measure | Use Case |
|---|---|
| Yield to Maturity (YTM) | Total return if held to maturity |
| Current Yield | Annual coupon / price |
| Yield to Call | Return if called at first call date |
| Spread to Benchmark | Credit risk premium over risk-free rate |
Duration and Convexity
| Metric | Measures |
|---|---|
| Macaulay Duration | Weighted average time to cash flows |
| Modified Duration | Price sensitivity to yield changes |
| Effective Duration | Duration for bonds with embedded options |
| Convexity | Second-order price sensitivity |
| Dollar Duration (DV01) | Dollar change per 1bp yield move |
Yield Curve Construction
| Method | Description |
|---|---|
| Bootstrap | Extract spot rates from par bond prices |
| Nelson-Siegel | Parametric model with level, slope, curvature |
| Nelson-Siegel-Svensson | Extended model with additional curvature term |
| Cubic Spline | Non-parametric interpolation |
DeFi Lending Rate Analysis
| Protocol | Chain | Type |
|---|---|---|
| Marginfi | Solana | Variable rate |
| Kamino | Solana | Variable rate |
| Solend | Solana | Variable rate |
| Aave | Ethereum/Multi | Variable + stable rate |
| Compound | Ethereum | Variable rate |
Planned DeFi features:
- Lending rate time series analysis
- Supply/borrow APY comparison across protocols
- Utilization rate impact on lending rates
- Fixed vs variable rate comparison (when fixed-rate protocols available)
- Rate arbitrage opportunity detection
---
Prerequisites
# For full implementation
uv pip install numpy scipy
# For visualization
uv pip install matplotlibThe included scripts/bond_calculator.py uses only the Python standard library and runs without any dependencies.
---
Use Cases
Yield Farming Comparison
Compare DeFi lending rates across protocols using fixed income analytics. Annualize variable rates, compute effective yields accounting for compounding frequency, and identify the most capital-efficient opportunities.
Lending Rate Analysis
Track lending rates over time to understand rate dynamics. Identify periods of rate compression (low utilization) vs rate expansion (high utilization) to time deposits optimally.
Rate Arbitrage
Borrow at lower rates on one protocol and lend at higher rates on another. Duration and convexity concepts help assess the risk of rate changes during the arbitrage holding period.
Risk Assessment
Use duration to estimate how lending positions change in value as rates move. Higher duration means greater sensitivity to rate changes.
---
Quick Reference: Bond Pricing Formulas
Bond price (present value of cash flows):
P = Σ [C / (1+y)^t] + F / (1+y)^n
t=1..n
Where:
C = periodic coupon payment = Face * coupon_rate / frequency
y = periodic yield = YTM / frequency
F = face value
n = total number of periodsMacaulay Duration:
D_mac = (1/P) * Σ [t * C / (1+y)^t] + (n * F) / ((1+y)^n * P)Modified Duration:
D_mod = D_mac / (1 + y)Convexity:
Convexity = (1/P) * Σ [t*(t+1) * C / (1+y)^(t+2)] + [n*(n+1)*F] / [(1+y)^(n+2) * P]Price change approximation:
ΔP/P ≈ -D_mod * Δy + 0.5 * Convexity * (Δy)²---
Files
| File | Description |
|---|---|
references/planned_features.md | Planned features, bond formulas, DeFi protocols, and implementation priorities |
scripts/bond_calculator.py | Bond price, YTM, duration, and convexity calculator |
---
Contributing
This skill is a stub awaiting full implementation. To contribute:
1. Implement yield curve bootstrapping from market data 2. Add Nelson-Siegel yield curve fitting 3. Build DeFi lending rate data fetcher (Marginfi, Kamino APIs) 4. Add day count convention support for accurate accrued interest 5. Create rate comparison dashboard across protocols
See references/planned_features.md for the full feature list and implementation priorities.
---
This skill provides analytical tools and mathematical models for informational purposes only. It does not constitute financial advice. Fixed income and DeFi lending involve risk of loss.
Fixed Income — Planned Features
Status: STUB — This document outlines the planned feature set for the fixed-income skill.
---
1. Bond Pricing (Implemented in stub)
Present Value of Cash Flows
The fundamental bond pricing equation:
P = Σ [C / (1+y)^t] + F / (1+y)^n
t=1..n
Where:
P = bond price (dirty price)
C = periodic coupon = Face * annual_coupon_rate / frequency
y = periodic yield = YTM / frequency
F = face (par) value
n = total coupon periods remainingClean vs Dirty Price
Clean Price = Dirty Price - Accrued Interest
Accrued Interest = C * (days since last coupon / days in coupon period)Day count conventions affect accrued interest calculation:
- 30/360: Assumes 30-day months, 360-day year
- ACT/360: Actual days elapsed, 360-day year
- ACT/365: Actual days elapsed, 365-day year
- ACT/ACT: Actual days in both numerator and denominator
Priority: Day count conventions are Medium priority for stub expansion.
---
2. Yield Measures
Yield to Maturity (Implemented — Newton's method solver)
YTM is the discount rate that equates the bond price to the present value of all future cash flows. Solved numerically since no closed-form solution exists for coupon bonds.
Current Yield (Implemented)
Current Yield = Annual Coupon / Clean PriceSimple but ignores time value and capital gains/losses.
Yield to Call (Planned)
For callable bonds, replace maturity with call date and face value with call price:
P = Σ [C / (1+y)^t] + Call_Price / (1+y)^n_callSpread Measures (Planned)
| Spread | Definition |
|---|---|
| Nominal Spread | YTM - Treasury YTM at same maturity |
| Z-Spread | Constant spread over zero curve |
| OAS | Spread over zero curve, adjusting for optionality |
Priority: Low for crypto context (no active crypto bond market yet).
---
3. Duration and Convexity (Implemented in stub)
Macaulay Duration
Weighted average time to receive cash flows:
D_mac = (1/P) * [Σ t*C/(1+y)^t + n*F/(1+y)^n]Interpretation: A bond with Macaulay duration of 5.2 years behaves like a zero-coupon bond maturing in 5.2 years.
Modified Duration
Price sensitivity per unit yield change:
D_mod = D_mac / (1 + y/freq)
ΔP/P ≈ -D_mod * ΔyA modified duration of 4.8 means a 1% yield increase causes approximately a 4.8% price decline.
Convexity
Second-order price sensitivity (curvature):
Convexity = (1/P) * Σ [t*(t+1)*CF_t / (1+y)^(t+2)]
ΔP/P ≈ -D_mod * Δy + 0.5 * Convexity * (Δy)²Convexity improves the duration approximation for large yield changes.
DV01 / Dollar Duration
Dollar value of a basis point:
DV01 = D_mod * P * 0.0001Priority: All duration/convexity measures are implemented in the stub calculator.
---
4. Yield Curve Construction (Planned)
Bootstrap Method
Extract spot (zero) rates from par bond prices sequentially:
1. Start with the shortest maturity bond to get the first spot rate 2. Use known spot rates to solve for the next spot rate 3. Repeat until the full curve is constructed
For a 2-period bond:
P = C/(1+z1) + (C+F)/(1+z2)^2
Solve for z2 given known z1Nelson-Siegel Model
Parametric yield curve with three factors:
y(τ) = β0 + β1 * [(1-e^(-τ/λ)) / (τ/λ)]
+ β2 * [(1-e^(-τ/λ)) / (τ/λ) - e^(-τ/λ)]
Where:
β0 = long-term rate level
β1 = slope (short-term component)
β2 = curvature (medium-term hump)
λ = decay factor
τ = time to maturityNelson-Siegel-Svensson Extension
Adds a second curvature term for more flexibility:
y(τ) = Nelson-Siegel + β3 * [(1-e^(-τ/λ2)) / (τ/λ2) - e^(-τ/λ2)]Priority: High — yield curve construction is fundamental for rate analysis.
---
5. DeFi Lending Protocols on Solana
Marginfi
- Variable-rate lending/borrowing
- Utilization-based rate model
- API: On-chain program data via Solana RPC
- Key metric: Supply APY, borrow APY, utilization rate
Kamino
- Automated lending vaults
- Concentrated liquidity integration
- API: REST API + on-chain data
- Key metric: Vault APY, leverage ratio
Solend
- Pool-based lending
- Multiple isolated pools by risk tier
- API: REST API at
api.solend.fi - Key metric: Pool APY, reserve utilization
Cross-Protocol Analysis (Planned)
- Rate comparison dashboard
- Historical rate time series
- Utilization-to-rate curve fitting
- Optimal deposit allocation across protocols
- Rate arbitrage detection (borrow low, lend high)
Rate Model Mathematics
Most DeFi protocols use a kinked utilization model:
If utilization ≤ optimal:
borrow_rate = base_rate + (utilization / optimal) * slope1
If utilization > optimal:
borrow_rate = base_rate + slope1 + ((utilization - optimal) / (1 - optimal)) * slope2
supply_rate = borrow_rate * utilization * (1 - reserve_factor)Priority: High — DeFi lending rate analysis is the primary crypto use case.
---
6. Implementation Priorities
| Priority | Feature | Complexity | Dependencies |
|---|---|---|---|
| 1 (Done) | Bond price calculator | Low | math stdlib |
| 2 (Done) | YTM solver | Low | math stdlib |
| 3 (Done) | Duration & convexity | Low | math stdlib |
| 4 | Day count conventions | Low | datetime |
| 5 | Yield curve bootstrap | Medium | numpy |
| 6 | Nelson-Siegel fitting | Medium | scipy |
| 7 | DeFi rate data fetcher | Medium | httpx |
| 8 | Rate comparison tool | Medium | httpx, pandas |
| 9 | Rate model curve fitting | Medium | scipy |
| 10 | Fixed vs variable analysis | High | numpy, scipy |
---
7. Crypto-Specific Considerations
- No standard maturities: DeFi lending is mostly variable rate with no fixed term
- Continuous compounding: Many protocols compound per block or per slot
- Utilization-driven rates: Rates change with pool utilization, unlike fixed coupon bonds
- Smart contract risk: Lending rate analysis must account for protocol risk premium
- Cross-chain rates: Same protocol may offer different rates on different chains
- Token incentives: Effective yield includes token rewards (emissions) on top of base APY
---
This document is for informational and planning purposes only. It does not constitute financial advice.
#!/usr/bin/env python3
"""Bond pricing calculator with YTM, duration, and convexity analysis.
This is a STUB implementation providing core fixed income calculations
using only the Python standard library. No external dependencies required.
Usage:
python scripts/bond_calculator.py --demo
Dependencies:
None (uses only Python standard library math module)
Environment Variables:
None required
"""
import argparse
import math
import sys
from typing import NamedTuple
# ── Data Structures ────────────────────────────────────────────────
class BondMetrics(NamedTuple):
"""Complete bond analysis result."""
dirty_price: float
current_yield: float
macaulay_duration: float
modified_duration: float
convexity: float
dv01: float
# ── Bond Pricing ───────────────────────────────────────────────────
def bond_price(
face: float,
coupon_rate: float,
ytm: float,
periods: int,
freq: int = 2,
) -> float:
"""Calculate bond price as present value of all cash flows.
Args:
face: Face (par) value of the bond.
coupon_rate: Annual coupon rate (decimal, e.g., 0.05 for 5%).
ytm: Yield to maturity (annual, decimal).
periods: Number of coupon periods remaining.
freq: Coupon frequency per year (1=annual, 2=semi-annual, 4=quarterly).
Returns:
Bond dirty price.
Raises:
ValueError: If inputs are invalid.
"""
if face <= 0:
raise ValueError(f"Face value must be positive, got {face}")
if coupon_rate < 0:
raise ValueError(f"Coupon rate must be non-negative, got {coupon_rate}")
if periods <= 0:
raise ValueError(f"Periods must be positive, got {periods}")
if freq not in (1, 2, 4, 12):
raise ValueError(f"Frequency must be 1, 2, 4, or 12, got {freq}")
coupon = face * coupon_rate / freq
y = ytm / freq
if abs(y) < 1e-12:
# Zero yield edge case: simple sum
return coupon * periods + face
pv_coupons = sum(coupon / (1 + y) ** t for t in range(1, periods + 1))
pv_face = face / (1 + y) ** periods
return pv_coupons + pv_face
def zero_coupon_price(face: float, ytm: float, years: float) -> float:
"""Price a zero-coupon bond.
Args:
face: Face value.
ytm: Yield to maturity (annual, decimal, continuously compounded).
years: Time to maturity in years.
Returns:
Zero-coupon bond price.
"""
if face <= 0:
raise ValueError(f"Face value must be positive, got {face}")
if years <= 0:
raise ValueError(f"Years must be positive, got {years}")
return face * math.exp(-ytm * years)
# ── Yield to Maturity Solver ──────────────────────────────────────
def yield_to_maturity(
price: float,
face: float,
coupon_rate: float,
periods: int,
freq: int = 2,
tol: float = 1e-8,
max_iter: int = 200,
) -> float:
"""Solve for yield to maturity using Newton's method.
Args:
price: Current bond price (dirty).
face: Face (par) value.
coupon_rate: Annual coupon rate (decimal).
periods: Number of coupon periods remaining.
freq: Coupon frequency per year.
tol: Convergence tolerance.
max_iter: Maximum iterations.
Returns:
Annual yield to maturity (decimal).
Raises:
ValueError: If solver does not converge.
"""
if price <= 0:
raise ValueError(f"Price must be positive, got {price}")
coupon = face * coupon_rate / freq
# Initial guess based on current yield approximation
annual_coupon = face * coupon_rate
ytm_guess = annual_coupon / price
if ytm_guess <= 0:
ytm_guess = 0.05 # fallback
y = ytm_guess / freq # periodic yield guess
for iteration in range(max_iter):
# Price as function of periodic yield
pv = 0.0
dpv = 0.0 # derivative of price w.r.t. y
for t in range(1, periods + 1):
discount = (1 + y) ** t
pv += coupon / discount
dpv -= t * coupon / ((1 + y) ** (t + 1))
pv += face / (1 + y) ** periods
dpv -= periods * face / ((1 + y) ** (periods + 1))
diff = pv - price
if abs(diff) < tol:
return y * freq
if abs(dpv) < 1e-15:
raise ValueError("Derivative too small — solver stuck")
y = y - diff / dpv
# Guard against negative yields going too extreme
if y < -0.5:
y = -0.5
if y > 2.0:
y = 2.0
raise ValueError(
f"YTM solver did not converge after {max_iter} iterations. "
f"Last estimate: {y * freq:.6f}"
)
# ── Duration and Convexity ─────────────────────────────────────────
def macaulay_duration(
face: float,
coupon_rate: float,
ytm: float,
periods: int,
freq: int = 2,
) -> float:
"""Calculate Macaulay duration in years.
Macaulay duration is the weighted average time to receive cash flows,
where weights are the present values of each cash flow.
Args:
face: Face value.
coupon_rate: Annual coupon rate (decimal).
ytm: Annual yield to maturity (decimal).
periods: Number of coupon periods remaining.
freq: Coupon frequency per year.
Returns:
Macaulay duration in years.
"""
coupon = face * coupon_rate / freq
y = ytm / freq
price = bond_price(face, coupon_rate, ytm, periods, freq)
weighted_sum = 0.0
for t in range(1, periods + 1):
pv_cf = coupon / (1 + y) ** t
weighted_sum += (t / freq) * pv_cf
# Add face value at maturity
pv_face = face / (1 + y) ** periods
weighted_sum += (periods / freq) * pv_face
return weighted_sum / price
def modified_duration(
face: float,
coupon_rate: float,
ytm: float,
periods: int,
freq: int = 2,
) -> float:
"""Calculate modified duration.
Modified duration measures the percentage price change for a 1%
change in yield: ΔP/P ≈ -D_mod * Δy
Args:
face: Face value.
coupon_rate: Annual coupon rate (decimal).
ytm: Annual yield to maturity (decimal).
periods: Number of coupon periods remaining.
freq: Coupon frequency per year.
Returns:
Modified duration in years.
"""
mac_dur = macaulay_duration(face, coupon_rate, ytm, periods, freq)
return mac_dur / (1 + ytm / freq)
def convexity(
face: float,
coupon_rate: float,
ytm: float,
periods: int,
freq: int = 2,
) -> float:
"""Calculate bond convexity.
Convexity measures the curvature of the price-yield relationship,
providing a second-order correction to the duration approximation.
Args:
face: Face value.
coupon_rate: Annual coupon rate (decimal).
ytm: Annual yield to maturity (decimal).
periods: Number of coupon periods remaining.
freq: Coupon frequency per year.
Returns:
Convexity (in years squared, scaled by freq²).
"""
coupon = face * coupon_rate / freq
y = ytm / freq
price = bond_price(face, coupon_rate, ytm, periods, freq)
conv_sum = 0.0
for t in range(1, periods + 1):
cf = coupon
if t == periods:
cf += face
conv_sum += t * (t + 1) * cf / (1 + y) ** (t + 2)
return conv_sum / (price * freq ** 2)
# ── Full Analysis ──────────────────────────────────────────────────
def analyze_bond(
face: float,
coupon_rate: float,
ytm: float,
periods: int,
freq: int = 2,
) -> BondMetrics:
"""Perform complete bond analysis.
Args:
face: Face value.
coupon_rate: Annual coupon rate (decimal).
ytm: Annual yield to maturity (decimal).
periods: Number of coupon periods remaining.
freq: Coupon frequency per year.
Returns:
BondMetrics with price, yield, duration, convexity, and DV01.
"""
price = bond_price(face, coupon_rate, ytm, periods, freq)
cur_yield = (face * coupon_rate) / price if price > 0 else 0.0
mac_dur = macaulay_duration(face, coupon_rate, ytm, periods, freq)
mod_dur = mac_dur / (1 + ytm / freq)
conv = convexity(face, coupon_rate, ytm, periods, freq)
dv01 = mod_dur * price * 0.0001 # dollar value of 1 basis point
return BondMetrics(
dirty_price=price,
current_yield=cur_yield,
macaulay_duration=mac_dur,
modified_duration=mod_dur,
convexity=conv,
dv01=dv01,
)
def price_change_estimate(
mod_dur: float, conv: float, price: float, yield_change_bps: float
) -> float:
"""Estimate price change using duration and convexity.
Args:
mod_dur: Modified duration.
conv: Convexity.
price: Current bond price.
yield_change_bps: Yield change in basis points (e.g., 50 for +50bp).
Returns:
Estimated dollar price change.
"""
dy = yield_change_bps / 10000.0
pct_change = -mod_dur * dy + 0.5 * conv * dy ** 2
return price * pct_change
# ── Demo ────────────────────────────────────────────────────────────
def run_demo() -> None:
"""Run demonstration calculations showing all capabilities."""
print("=" * 60)
print(" Fixed Income Bond Calculator — STUB Demo")
print(" For informational purposes only. Not financial advice.")
print("=" * 60)
# Example 1: Standard coupon bond
face = 1000.0
coupon_rate = 0.05 # 5% annual coupon
ytm = 0.06 # 6% yield (bond trades at a discount)
years = 10
freq = 2 # semi-annual
periods = years * freq
print(f"\n--- Example 1: {coupon_rate:.0%} Coupon Bond, {years}-Year ---")
print(f" Face Value: ${face:,.0f}")
print(f" Coupon Rate: {coupon_rate:.2%} (semi-annual)")
print(f" YTM: {ytm:.2%}")
print(f" Maturity: {years} years ({periods} periods)")
metrics = analyze_bond(face, coupon_rate, ytm, periods, freq)
print(f"\n Results:")
print(f" Price: ${metrics.dirty_price:,.4f}")
print(f" Current Yield: {metrics.current_yield:.4%}")
print(f" Macaulay Duration: {metrics.macaulay_duration:.4f} years")
print(f" Modified Duration: {metrics.modified_duration:.4f}")
print(f" Convexity: {metrics.convexity:.4f}")
print(f" DV01: ${metrics.dv01:.4f}")
# Price change scenarios
print(f"\n Price Change Estimates:")
for bps in [-100, -50, 50, 100]:
delta_p = price_change_estimate(
metrics.modified_duration, metrics.convexity,
metrics.dirty_price, bps
)
new_price = metrics.dirty_price + delta_p
print(f" {bps:+d} bps: ${delta_p:+,.2f} → ${new_price:,.2f}")
# Example 2: Premium bond
print(f"\n--- Example 2: Premium Bond (coupon > yield) ---")
ytm2 = 0.03
metrics2 = analyze_bond(face, coupon_rate, ytm2, periods, freq)
print(f" {coupon_rate:.0%} coupon, {ytm2:.0%} yield")
print(f" Price: ${metrics2.dirty_price:,.4f} (premium)")
print(f" Modified Duration: {metrics2.modified_duration:.4f}")
# Example 3: Zero coupon bond
print(f"\n--- Example 3: Zero-Coupon Bond ---")
zc_face = 1000.0
zc_ytm = 0.04
zc_years = 5.0
zc_price = zero_coupon_price(zc_face, zc_ytm, zc_years)
print(f" Face: ${zc_face:,.0f}, Yield: {zc_ytm:.0%}, Maturity: {zc_years:.0f} years")
print(f" Price: ${zc_price:,.4f}")
print(f" Duration: {zc_years:.1f} years (always equals maturity for zeros)")
# Example 4: YTM solver
print(f"\n--- Example 4: YTM Solver ---")
known_price = 925.0
solved_ytm = yield_to_maturity(known_price, face, coupon_rate, periods, freq)
verify_price = bond_price(face, coupon_rate, solved_ytm, periods, freq)
print(f" Given price: ${known_price:,.2f}")
print(f" Solved YTM: {solved_ytm:.6%}")
print(f" Verify price: ${verify_price:,.4f}")
print(f" Error: ${abs(verify_price - known_price):.6f}")
# Example 5: DeFi rate comparison context
print(f"\n--- DeFi Lending Rate Context ---")
print(f" (Planned feature — stub placeholder)")
print(f" Traditional 10Y bond yield: ~{ytm:.1%}")
print(f" Solana lending rates: ~5-15% variable APY")
print(f" Key difference: DeFi rates are variable and")
print(f" change with pool utilization, while bonds pay")
print(f" fixed coupons. Duration analysis helps compare")
print(f" the interest rate risk of each approach.")
print(f"\n{'=' * 60}")
print(f" Demo complete. All calculations are for illustration only.")
print(f"{'=' * 60}")
# ── Main ────────────────────────────────────────────────────────────
def main() -> None:
"""Parse arguments and run."""
parser = argparse.ArgumentParser(
description="Bond pricing calculator (STUB)"
)
parser.add_argument(
"--demo",
action="store_true",
help="Run demonstration with example calculations",
)
parser.add_argument("--face", type=float, default=1000.0, help="Face value (default: 1000)")
parser.add_argument("--coupon", type=float, help="Annual coupon rate (decimal, e.g., 0.05)")
parser.add_argument("--ytm", type=float, help="Yield to maturity (decimal, e.g., 0.06)")
parser.add_argument("--years", type=float, help="Years to maturity")
parser.add_argument("--freq", type=int, default=2, help="Coupon frequency (default: 2)")
parser.add_argument(
"--solve-ytm", type=float, metavar="PRICE",
help="Solve for YTM given this bond price"
)
args = parser.parse_args()
if args.demo:
run_demo()
return
if args.solve_ytm is not None:
if not all([args.coupon is not None, args.years]):
print("Error: --coupon and --years required for --solve-ytm")
sys.exit(1)
periods = int(args.years * args.freq)
solved = yield_to_maturity(args.solve_ytm, args.face, args.coupon, periods, args.freq)
print(f"Solved YTM: {solved:.6%}")
return
if not all([args.coupon is not None, args.ytm is not None, args.years]):
print("Error: --coupon, --ytm, and --years are required (or use --demo)")
parser.print_help()
sys.exit(1)
periods = int(args.years * args.freq)
metrics = analyze_bond(args.face, args.coupon, args.ytm, periods, args.freq)
print(f"\nBond Analysis")
print(f" Price: ${metrics.dirty_price:,.4f}")
print(f" Current Yield: {metrics.current_yield:.4%}")
print(f" Macaulay Duration: {metrics.macaulay_duration:.4f} years")
print(f" Modified Duration: {metrics.modified_duration:.4f}")
print(f" Convexity: {metrics.convexity:.4f}")
print(f" DV01: ${metrics.dv01:.4f}")
if __name__ == "__main__":
main()