К основному содержанию
скилл CX Codex

fixed-income-sovereign — скилл для Claude Code: аналитика US

Считает цены облигаций, дюрацию, выпуклость и кривую доходности по US Treasuries. Пригодится, когда нужно разобрать процентный риск, а не гадать по формулам.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add JoelLewis/finance_skills --skill fixed-income-sovereign -a claude-code
Открыть на GitHub

Что делает fixed-income-sovereign

Скилл закрывает аналитику американских гособлигаций: цена облигации из доходности, yield to maturity, current yield, спот- и форвардные ставки, бутстрэппинг кривой, дюрация Маколея и модифицированная, DV01, выпуклость, TIPS и безубыточная инфляция, key rate duration. Внутри — формулы с расшифровкой переменных и разобранные примеры: цена пятилетней бумаги с купоном 4% при доходности 5% и оценка изменения цены при сдвиге ставки на 50 базисных пунктов.

Есть скрипт scripts/fixed_income_sovereign.py, запускается через uv run с инлайн-зависимостями PEP 723. Флаг --verify сверяет результаты демо с примерами и возвращает код 1 при расхождении. Отдельный раздел про типичные ошибки: путаница дюрации Маколея с модифицированной, игнорирование выпуклости при крупных сдвигах ставки, соглашения о подсчёте дней (для Treasuries — actual/actual, для корпоратов — 30/360), чистая и грязная цена с накопленным купоном.

Суверенный кредитный риск вне области действия: долг развивающихся рынков, анализ дефолтов и страновые спреды скилл не разбирает. Это повод не тащить его в задачи про EM debt. Ещё он ссылается на соседние скиллы — time-value-of-money, fixed-income-corporate, fixed-income-municipal, asset-allocation, — так что без них часть контекста останется за кадром.

Какие задачи решает

  • посчитать цену облигации по заданной доходности
  • построить спот-кривую бутстрэппингом из par yields
  • оценить изменение цены при сдвиге ставки с поправкой на выпуклость
  • сравнить номинальную доходность с реальной по TIPS и найти безубыточную инфляцию
  • разложить процентный риск по key rate duration

Примеры запросов агенту

  • Посчитай цену 5-летней Treasury с купоном 4% и доходностью 5%, купон полугодовой
  • Оцени, как изменится цена облигации с дюрацией Маколея 4.5 года при росте ставки на 50 бп
  • Построй спот-кривую из par yields и выведи форвардные ставки между 2 и 5 годами

Как установить fixed-income-sovereign

1Через Skills CLI (Vercel)

npx skills add JoelLewis/finance_skills --skill fixed-income-sovereign -a claude-code

2Вручную: положить файлы

~/.claude/skills/fixed-income-sovereign/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/fixed-income-sovereign/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о fixed-income-sovereign

Как установить fixed-income-sovereign в Claude?

Выполните npx skills add JoelLewis/finance_skills --skill fixed-income-sovereign -a claude-code. Скилл появится в ~/.claude/skills/fixed-income-sovereign/SKILL.md.

Что делает fixed-income-sovereign?

Считает цену облигаций, доходность к погашению, дюрацию, выпуклость, DV01 и форвардные ставки по US Treasuries. Разбирает TIPS и безубыточную инфляцию, строит кривую доходности.

Разбирает ли скилл долг развивающихся рынков?

Нет. Суверенный кредитный риск — EM debt, дефолты, страновые спреды — вне области действия. Скилл работает только с US Treasuries и аналитикой ставок.

Исходный текст

SKILL.md · MIT
---
name: fixed-income-sovereign
description: "Analyze US Treasury securities and interest rate risk: bond pricing, yield curve construction, duration, convexity, TIPS, and forward/spot rate analysis. Use when the user asks about Treasury bonds, yield curve construction, interest rate risk, duration, convexity, TIPS, or breakeven inflation rates. Also trigger when users mention 'T-bills', 'T-notes', 'bond pricing', 'yield to maturity', 'inverted yield curve', 'forward rates', 'spot rates', 'DV01', 'real yields', or ask how bonds react to interest rate changes."
---

# Fixed Income — Sovereign

Scope: US Treasuries and rates analytics. Sovereign *credit* risk — emerging market debt, default analysis, country risk spreads — is out of scope for this skill.

## Core Concepts

### Bond Pricing
The price of a bond is the present value of its future cash flows:

P = sum(t=1 to n) [C / (1+y)^t] + F / (1+y)^n

where C = coupon payment per period, y = yield to maturity per period, F = face value, n = total number of periods. For semi-annual bonds, divide the annual coupon by 2 and the annual yield by 2, and double the number of years to get n.

### Yield to Maturity (YTM)
The discount rate y that solves the bond pricing equation — the single rate that equates the bond's market price to the present value of all future cash flows. Assumes reinvestment of coupons at the YTM rate. It is the standard yield measure for bonds.

### Current Yield
Current Yield = Annual Coupon / Price. A simple income measure that ignores capital gains/losses and the time value of money.

### Yield Curve: Spot Rates, Forward Rates, Par Curve
The spot curve gives zero-coupon yields for each maturity. The par curve gives coupon rates at which bonds would price at par. Forward rates are implied future rates derived from spot rates. The three curves contain equivalent information and can be derived from one another.

### Bootstrapping the Spot Curve
Extract spot (zero-coupon) rates from par yields by starting at the shortest maturity and working outward. Each step uses previously derived spot rates to solve for the next spot rate.

### Forward Rate
The implied rate between two future dates derived from spot rates:

f(t1,t2) = [(1+s_t2)^t2 / (1+s_t1)^t1]^(1/(t2-t1)) - 1

where s_t1 and s_t2 are spot rates for maturities t1 and t2.

### Duration (Macaulay)
The weighted average time to receive cash flows, where weights are the present value of each cash flow as a proportion of the bond's price:

D_mac = (1/P) × sum(t × CF_t / (1+y)^t)

Measured in years. Longer maturity, lower coupon, and lower yield all increase duration.

### Modified Duration
D_mod = D_mac / (1 + y/m)

where m = number of coupon periods per year. Gives the approximate percentage price change for a 1 percentage point change in yield: dP/P ≈ -D_mod × dy.

### Dollar Duration (DV01)
The dollar change in price for a 1 basis point change in yield:

DV01 ≈ -D_mod × P × 0.0001

Used for hedging — match DV01 exposures to immunize a portfolio against parallel rate shifts.

### Convexity
Measures the curvature of the price-yield relationship (second derivative):

C = (1/P) × sum(t(t+1) × CF_t / (1+y)^(t+2))

For option-free bonds, convexity is always positive — duration alone overstates losses and understates gains.

### Price Change Approximation
ΔP/P ≈ -D_mod × Δy + 0.5 × Convexity × (Δy)²

The convexity term is a correction that becomes important for large yield changes.

### TIPS (Treasury Inflation-Protected Securities)
Principal adjusts with CPI. The coupon rate is fixed but applied to the inflation-adjusted principal. Real yield = TIPS yield. Breakeven inflation = nominal Treasury yield - TIPS real yield. TIPS have a deflation floor that protects par value at maturity.

### Key Rate Duration
Sensitivity to specific points on the yield curve (e.g., 2yr, 5yr, 10yr, 30yr). Allows analysis of non-parallel yield curve shifts such as steepening, flattening, or butterfly moves. Sum of key rate durations equals effective duration.

## Key Formulas

| Formula | Expression | Use Case |
|---------|-----------|----------|
| Bond Price | P = sum C/(1+y)^t + F/(1+y)^n | Price from yield |
| Current Yield | Annual Coupon / Price | Simple income measure |
| Forward Rate | f(t1,t2) = [(1+s_t2)^t2 / (1+s_t1)^t1]^(1/(t2-t1)) - 1 | Implied future rate |
| Macaulay Duration | (1/P) × sum(t × CF_t / (1+y)^t) | Weighted avg time to cash flows |
| Modified Duration | D_mac / (1 + y/m) | % price sensitivity to yield |
| DV01 | D_mod × P × 0.0001 | Dollar price change per 1bp |
| Convexity | (1/P) × sum(t(t+1) × CF_t / (1+y)^(t+2)) | Curvature of price-yield curve |
| Price Change | ΔP/P ≈ -D_mod×Δy + 0.5×Convexity×(Δy)² | Estimate price impact of rate move |

## Worked Examples

### Example 1: Price a 5-Year 4% Semi-Annual Coupon Bond at 5% YTM
**Given:** Face = $1,000, coupon = 4% (semi-annual), YTM = 5%, maturity = 5 years
**Calculate:** Bond price
**Solution:**
Semi-annual coupon = $1,000 × 4% / 2 = $20
Semi-annual yield = 5% / 2 = 2.5%
Number of periods = 5 × 2 = 10
P = $20 × [(1 - (1.025)^(-10)) / 0.025] + $1,000 / (1.025)^10
P = $20 × 8.7521 + $1,000 × 0.7812
P = $175.04 + $781.20 = $956.24

The bond trades at a discount ($956.24 < $1,000) because the coupon rate (4%) is below the market yield (5%).

### Example 2: Modified Duration and Price Change Estimate
**Given:** A bond with Macaulay duration = 4.5 years, YTM = 5% (semi-annual), price = $956.24, convexity = 22.5
**Calculate:** Estimated price change for a +50bp rate increase
**Solution:**
D_mod = 4.5 / (1 + 0.05/2) = 4.5 / 1.025 = 4.39 years
ΔP/P ≈ -4.39 × 0.005 + 0.5 × 22.5 × (0.005)²
ΔP/P ≈ -0.02195 + 0.000281 = -0.02167 = -2.167%
ΔP ≈ -2.167% × $956.24 = -$20.72
New price ≈ $956.24 - $20.72 = $935.52

Duration alone would estimate -2.195%; the convexity correction reduces the estimated loss by about 3bp.

## Common Pitfalls
- Confusing Macaulay and modified duration — Macaulay is in years, modified gives price sensitivity
- Ignoring convexity for large yield changes — duration alone overstates losses and understates gains
- Day count conventions (30/360 vs actual/actual) — Treasuries use actual/actual, corporates use 30/360
- Clean price vs dirty price (accrued interest) — quoted prices exclude accrued interest, but settlement requires paying it

## Cross-References
- **time-value-of-money** (core plugin): discounting and present value fundamentals
- **fixed-income-corporate** (wealth-management plugin): credit spreads over the sovereign curve
- **fixed-income-municipal** (wealth-management plugin): muni-to-Treasury yield ratios
- **asset-allocation** (wealth-management plugin): bonds as an asset class in portfolio construction

## Running the Script

```bash
uv run scripts/fixed_income_sovereign.py            # run the demo (uses PEP 723 inline deps)
uv run scripts/fixed_income_sovereign.py --verify   # check demo outputs against the worked examples (exit 1 on mismatch)
python3 scripts/fixed_income_sovereign.py            # alternative (requires: pip install numpy scipy)
```

The demo prints the calculations covered above; its values match the worked examples in this skill. Run `--help` for a list of the classes and functions. For programmatic use, import the module rather than running it — the demo only executes under `python fixed_income_sovereign.py`.

© JoelLewis · MIT · JoelLewis/finance_skills

Похожие скиллы

Всё по теме «Финансы и бизнес» →
fixed-income-portfolio официальный anthropics Скилл для анализа портфелей облигаций: цены, дюрация, DV01, сценарии ставок и кэшфлоу-прогнозы. Агрегирует данные из MCP-инструментов в отчёт с метриками риска. CX Codex +1 1 800установок macro-rates-monitor официальный anthropics Скилл строит сводки по макроэкономике и процентным ставкам. Он сводит данные по инфляции, кривым доходности и свопам в единый аналитический отчёт. CX Codex +1 2 300установок om-close-fixed-issues open-mercato Закрывает решённые задачи в трекере после слияния пуллреквестов и оставляет комментарии к закрытым без слияния PR. Пригодится перед релизом и после массовых мерджей. CX Codex +1 2 700установок sticky-and-fixed-elements dembrandt Помогает решить, что остаётся на экране при прокрутке: липкие заголовки, нижние панели, плавающие кнопки, закреплённые шапки таблиц. CX Codex +1 855установок affiliate-payout-audit Maya-Beth Finotti Проверяет расчёт партнёрских комиссий до перевода денег: пересчитывает ставки и уровни, ищет дубли конверсий, проверяет окна валидации и налоговые формы. CX Codex +1 13 500установок k-dart NomaDamas Скилл для поиска данных в DART (Электронная система공시 Корейской комиссии по финансовому надзору). Ищет публикации, финансовые отчёты и сведения о компаниях через OpenAPI. CX Codex +1 6 500установок

Из того же набора59

digital-assets Скилл для разбора криптовалют: фундаментал, механика блокчейнов, DeFi-протоколы и метрики ончейна. Пригодится, когда нужно посчитать доходность стейкинга или оценить токен. CX Codex +1 683установок tax-loss-harvesting Ведёт скилл по всему циклу налогового харвестинга: поиск кандидатов, бюджет прибылей и убытков, подбор замены, контроль wash-sale. CX Codex +1 683установок next-best-action Скилл проектирует движки next-best-action: система сама находит события по портфелю клиента и предлагает советнику, что делать дальше. CX Codex +1 680установок know-your-customer Скилл ведёт агента по требованиям KYC: проверка личности, бенефициарные владельцы, EDD для PEP и обновление профиля клиента. CX Codex +1 679установок settlement-clearing Скилл для работы с расчётами по сделкам: цикл T+1, инфраструктура DTC/NSCC/FICC, неттинг CNS, несогласованные поставки и процедуры buy-in. CX Codex +1 669установок performance-attribution Раскладывает доходность портфеля на объяснимые части: сколько дал выбор секторов, сколько — выбор бумаг внутри них. Пригодится, когда нужно понять, почему портфель обогнал или отстал от бенчмарка. CX Codex +1 668установок client-onboarding Помогает спроектировать путь клиента от первого контакта до пополненного счёта: KYC, документы, подпись, отправка кастодиану. CX Codex +1 670установок advice-standards Помогает понять, когда фича, приложение или текст перестают быть просвещением и становятся инвестиционным советом с обязанностью регистрации советника. CX Codex +1 669установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой