trader-portfolio-cg — скилл для Claude Code: оптимизация портфеля
Решает задачу mean-variance через сопряжённые градиенты вместо ряда Неймана. Нужен, когда пересчитываете веса портфеля часто и упираетесь в задержку.
npx skills add ruvnet/ruflo --skill trader-portfolio-cg -a claude-codeЧто делает trader-portfolio-cg
Скилл решает систему Σ · x = μ методом сопряжённых градиентов. Ковариационная матрица Σ симметрична и положительно определена по построению, поэтому CG сходится максимум за n итераций без предобусловливания, а при кластеризации собственных значений — заметно быстрее. Заявленное ускорение против старого пути через ряд Неймана — 40-60×, расхождение с ним в пределах 1e-4 на фиксированном seed.
Внутри — адаптер sublinearAdapter, который сам выбирает бэкенд: пробует нативный mcp__ruflo-sublinear__solve, а если тот недоступен, уходит на встроенную JS-реализацию CG примерно на 50 строк. Математика одна и та же. В метаданных артефакта остаётся method — cg-sublinear-native, cg-local или neumann-fallback, так что видно, кто считал.
Перед запуском проверьте, что у вас есть откуда взять Σ и μ: neural-trader 2.8.11 их не возвращает, --portfolio current гоняет демо с равными весами. Матрицу доходностей придётся передать самому или достать из AgentDB, где её сохранил прошлый прогон. Веса складываются в namespace trading-risk без TTL — это аудиторский след. Если новая раскладка отличается от исторической медианы больше чем на 30% по любому активу, скилл советует отправить результат на ручную проверку.
Какие задачи решает
- посчитать оптимальные веса портфеля на матрице 256×256
- ускорить пересчёт mean-variance без смены математики
- сравнить CG и старый путь Неймана на одном seed
- сохранить веса вместе с методом и числом итераций
- поймать расхождение новых весов с исторической медианой
Примеры запросов агенту
- посчитай оптимальные веса портфеля через trader-portfolio-cg, tolerance 1e-6
- прогони trader-portfolio-cg на ковариационной матрице из AgentDB
- сравни результат trader-portfolio-cg с fallback-путём Неймана
Как установить trader-portfolio-cg
1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill trader-portfolio-cg -a claude-code2Вручную: положить файлы
~/.claude/skills/trader-portfolio-cg/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/trader-portfolio-cg/
1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill trader-portfolio-cg -a codex2Вручную: положить файлы
.agents/skills/trader-portfolio-cg/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill trader-portfolio-cg -a cursor2Вручную: положить файлы
.cursor/skills/trader-portfolio-cg/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install ruvnet/ruflo trader-portfolio-cg2Вручную: положить файлы
.github/skills/trader-portfolio-cg/SKILL.md1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill trader-portfolio-cg -a gemini-cli2Командой платформы
gemini skills install https://github.com/ruvnet/ruflo --path plugins/ruflo-neural-trader/skills/trader-portfolio-cgВручную: положить файлы
.devin/skills/trader-portfolio-cg/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill trader-portfolio-cg -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о trader-portfolio-cg
Как установить trader-portfolio-cg в Claude?
Выполните npx skills add ruvnet/ruflo --skill trader-portfolio-cg -a claude-code. После этого файл скилла лежит в ~/.claude/skills/trader-portfolio-cg/SKILL.md.
Что делает trader-portfolio-cg?
Решает систему Σ · x = μ сопряжёнными градиентами и получает оптимальные веса портфеля. Результат с метаданными о методе и числе итераций уходит в namespace trading-risk.
Что нужно, чтобы скилл заработал?
Нужны ковариационная матрица и вектор ожидаемых доходностей: neural-trader их не отдаёт, берите у пользователя или из AgentDB. Ещё нужен пакет neural-trader для fallback-пути.
Исходный текст
SKILL.md · MIT
---
name: trader-portfolio-cg
description: Mean-variance portfolio optimization via Conjugate Gradient — 40-60× faster than the legacy Neumann path (ADR-126 Phase 3, ADR-123 Wedge 8)
allowed-tools: Bash Read mcp__ruflo-sublinear__solve mcp__plugin_ruflo-core_ruflo__memory_store mcp__plugin_ruflo-core_ruflo__memory_retrieve mcp__plugin_ruflo-core_ruflo__memory_search mcp__plugin_ruflo-core_ruflo__agentdb_pattern-search
argument-hint: "[--portfolio-id ID] [--tolerance 1e-6]"
---
Solve the mean-variance optimization `Σ · x = μ` via Conjugate Gradient instead of the legacy Neumann series.
**Why CG instead of Neumann (ADR-123 Wedge 8):**
- Neumann series: ~50 µs at n=256 (legacy `npx neural-trader --portfolio optimize`)
- Conjugate Gradient: ~816 ns at n=256 (this skill)
- Measured speedup: 40-60×; parity within 1e-4 on a fixed seed.
The covariance matrix Σ is symmetric positive-definite by construction (it's a Gram matrix on real returns), so CG is provably optimal — it converges in at most n iterations with no preconditioning, and typically far fewer when eigenvalues cluster.
**Disable flag**: set `RUFLO_NEURAL_TRADER_DISABLE_CG=1` to skip the CG path entirely and fall through to step 4's legacy Neumann route. Useful for A/B validation or when an upstream covariance regression breaks SPD.
**Native dispatch flag**: set `RUFLO_SUBLINEAR_NATIVE=1` to force the adapter to attempt the native `mcp__ruflo-sublinear__solve` path even when `globalThis` doesn't expose the tool (e.g. when the harness mounts it via a different transport). On any native-dispatch failure the adapter cleanly falls back to the local JS CG and records `method: 'cg-local'` in the artifact metadata — so the regression is auditable.
Steps:
1. **Ensure neural-trader is available**:
```bash
npm ls neural-trader 2>/dev/null || npm install --ignore-scripts neural-trader
```
2. **Read the current covariance matrix Σ and expected-return vector μ** from neural-trader's portfolio API:
```bash
# neural-trader 2.8.11 does NOT return Σ or μ: `--portfolio current` runs the equal-weight demo
# (symbols, weights, a risk figure and a note that the returns matrix is not wired).
# Take Σ and μ from the user (a returns matrix they provide), or from AgentDB if a prior run stored them:
```
```text
mcp__plugin_ruflo-core_ruflo__memory_search({ query: "covariance matrix current", namespace: "trading-risk", limit: 1 })
```
The skill expects the response to include `covariance: number[][]` (n × n) and `expectedReturns: number[]` (length n).
3. **Solve Σ · x = μ via the SublinearAdapter** (preferred path) when `RUFLO_NEURAL_TRADER_DISABLE_CG` is unset:
```js
import { sublinearAdapter } from '../../src/sublinear-adapter.mjs';
const result = await sublinearAdapter.solveCG(COVARIANCE, EXPECTED_RETURNS, {
tolerance: 1e-6,
maxIterations: 200,
});
// result.solution — optimal weights (number[])
// result.iterations — CG iterations executed
// result.residual — final ||A·x − b||₂
// result.latencyMs — wall-clock latency
// result.method — 'cg-sublinear-native' | 'cg-local' <-- READ THIS
// result.solver — '[email protected]' | 'local-js-cg'
// result.degraded — true if input failed SPD checks (fall back to step 4)
```
The adapter does the dispatch itself: it probes for `mcp__ruflo-sublinear__solve` on `globalThis` (and honours `RUFLO_SUBLINEAR_NATIVE=1` as a manual override), routes through the native kernel when reachable, and falls back transparently to the embedded ~50-LOC JS CG when not. The math is identical either way — CG, dense form, n × n SPD covariance. The operator reads `result.method` to know which backend produced the artifact.
The native MCP tool's wire shape (for direct callers who want to bypass the adapter):
```text
mcp__ruflo-sublinear__solve({
matrix: COVARIANCE,
rhs: EXPECTED_RETURNS,
algorithm: "cg",
tolerance: 1e-6,
maxIterations: 200
})
```
Output:
```ts
{ solution: number[], iterations: number, residual: number }
```
4. **Fallback (legacy Neumann)** — if step 3 reports `degraded: true` (non-SPD input, non-square matrix, MCP error) OR if `RUFLO_NEURAL_TRADER_DISABLE_CG=1`:
```bash
npx neural-trader --portfolio optimize
```
Capture the weights output and tag the artifact metadata with `method: 'neumann-fallback'` and a `reason` field.
5. **Store the optimal weights** to `trading-risk` namespace with full provenance metadata. **Take `method` and `solver` straight from the adapter's result so the operator can verify which backend ran**:
```text
mcp__plugin_ruflo-core_ruflo__memory_store({
key: "portfolio-weights-PORTFOLIO_ID-TIMESTAMP",
namespace: "trading-risk",
value: JSON.stringify({
weights: result.solution, // number[] from step 3 (or weights from step 4 fallback)
method: result.method, // 'cg-sublinear-native' | 'cg-local' | 'neumann-fallback'
solver: result.solver, // '[email protected]' | 'local-js-cg' | 'neural-trader-cli'
iterations: result.iterations,
residual: result.residual,
latencyMs: result.latencyMs,
capturedAt: NEW_DATE_ISO,
reason: FALLBACK_REASON || null
})
})
```
The `trading-risk` namespace is canonical (ADR-126 Phase 1; the five-namespace alignment). Long-lived — no TTL — because portfolio weights are the audit trail Phase 4 will Ed25519-sign.
6. **Cross-check against historical patterns** (optional but recommended):
```text
mcp__plugin_ruflo-core_ruflo__agentdb_pattern-search({
query: "portfolio weights Sharpe regime:CURRENT_REGIME",
namespace: "trading-risk"
})
```
If the new weights differ by more than 30% in any single asset from the historical median, flag for human review before applying. This is a guard-rail, not a hard block.
**Acceptance criteria (ADR-126 Phase 3):**
- Latency < 1 ms on n = 256 covariance (local JS CG); native path target 40-60× faster (816 ns native vs 50 µs Neumann per [email protected]).
- Parity with legacy Neumann within `||cg − neumann||_∞ < 1e-4` on a fixed seed.
- Fallback path engages cleanly when native MCP unavailable / covariance non-SPD.
- Artifact metadata distinguishes `cg-sublinear-native`, `cg-local`, and `neumann-fallback`.
**Refs**:
- ADR-126 Phase 3 (this skill's authoring ADR)
- ADR-123 §162 Row 8 (Wedge 8 speedup claim)
- ADR-123 §262-289 (the SublinearAdapter contract)
- `plugins/ruflo-neural-trader/src/sublinear-adapter.ts` (the adapter)
- `plugins/ruflo-neural-trader/benchmarks/portfolio-cg.bench.ts` (the measured numbers)
© ruvnet · MIT · ruvnet/ruflo