Skip to content
cccskills
FreePublished on GitHubEnglish overview

trader-portfolio-cg

Calculate portfolio weights from a covariance matrix, which describes how asset returns move together, and expected returns using Conjugate Gradient. Save the weights with the solver used, numerical error, and timing so the calculation can be checked later.

OriginalShow the original description

Mean-variance portfolio optimization via Conjugate Gradient — 40-60× faster than the legacy Neumann path (ADR-126 Phase 3, ADR-123 Wedge 8)

AI rating80/ 100See how to install

Good for

  • Calculating portfolio weights from supplied return data
  • Comparing Conjugate Gradient with the legacy calculation
  • Keeping records of weights and calculation details
  • Flagging large differences from historical allocations

Overview

What it does

Calculate portfolio allocations from a covariance matrix, which describes how asset returns move together, and expected returns. The skill uses Conjugate Gradient, an iterative method for solving systems of equations. If the native MCP implementation is unavailable, it switches to a local JavaScript implementation. It saves the allocations together with the calculation method, iteration count, numerical error, and elapsed time.

When it helps

Use it when you have input data ready for an allocation calculation or want to compare results with the legacy Neumann method. It also supports comparing new allocations with historical allocations and flagging large changes in individual assets for human review.

Example requests

  • “Calculate allocations using this covariance matrix and these expected returns.”
  • “Save the results, including the calculation method and numerical error.”
  • “Compare these allocations with historical allocations and report large differences.”

Notes

The skill uses neural-trader, a dedicated adapter, and MCP storage tools. Since neural-trader 2.8.11 does not return the required matrix and expected returns, inputs must come from the user or previously stored data. Conjugate Gradient requires a symmetric positive-definite matrix. The skill switches to the legacy method when input requirements are not met or other fallback conditions apply. Speed comparisons in the source were measured under specific conditions.

This overview was written by AI (OpenAI Codex) from the public SKILL.md. Check the original below for the exact behavior.

Objective evaluation

AI rated this skill on four points using only the contents of its SKILL.md. Stars and popularity are not taken into account.

Clear instructionsIs it clear when to use it and what it does?
AGoodIt explicitly calculates allocations from covariance and expected returns, then stores verification metadata.
Concrete stepsAre steps, inputs, outputs, and examples spelled out?
AGoodInput array shapes, solveCG arguments, fallback paths, and stored fields are specified.
SafetyAre sending data, deleting files, and running commands disclosed?
BPartly lackingIt runs npm install and stores data through MCP, but does not specify confirmation before these operations.
Easy setupDoes it need few tools or API keys, and are they documented?
BPartly lackingA neural-trader installation command is provided, but setup instructions for the dedicated adapter and MCP tools are incomplete.

The total counts each point as A = 25, B = 15, C = 5. Rated by AI (OpenAI Codex) as of Oct 21, 2026. Treat it as a guide and read the original before installing.

Disagree? Request a re-evaluation

Tell us which point is wrong and why. No login needed. We will check it against the SKILL.md, redo the evaluation, and show the result here.

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

Files included (1)

  • SKILL.md6.6 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

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:

    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:

    # 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:
    
    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:

    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      — 'sublinear-time-solver@1.7.0' | '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):

    mcp__ruflo-sublinear__solve({
      matrix: COVARIANCE,
      rhs: EXPECTED_RETURNS,
      algorithm: "cg",
      tolerance: 1e-6,
      maxIterations: 200
    })
    

    Output:

    { 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:

    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:

    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,              // 'sublinear-time-solver@1.7.0' | '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):

    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 sublinear-time-solver@1.7.0).
  • 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)

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

add-model-descriptions

FreeSummaryAI rating 80

Compare models available through the HuggingFace router with chat-ui configuration, research missing models, and write short English descriptions of their architecture and capabilities. Add entries to both production and development configuration files and commit the changes.

  • Adding newly available router models to chat-ui
  • Writing concise descriptions of model capabilities
  • Updating production and development model entries together
ruvnet/ruflo78.3KUpdated Oct 21, 2026

adr-create

FreeSummaryAI rating 80

Create an Architecture Decision Record, a document for recording important design choices, with the next sequential number. It generates a Markdown template, registers the record in AgentDB, and links related decisions found through search.

  • Record the reasoning behind adopting a technology
  • Start an ADR for an API or data model change
  • Document an infrastructure decision
ruvnet/ruflo78.3KUpdated Oct 21, 2026

adr-index

FreeSummaryAI rating 90

Build a searchable index and relationship graph from ADRs, records of architectural decisions. Import two supported document formats, refresh existing metadata without duplicate relationships, and review summaries of statuses, missing references, and inconsistencies.

  • Index ADRs imported from another project
  • Refresh a graph that differs from files on disk
  • Set up ADR tracking in an existing codebase
ruvnet/ruflo78.3KUpdated Oct 21, 2026

adr-reindex

FreeSummaryAI rating 70

Rebuild the index of ADRs, records of architectural decisions, after files or relationship lines are deleted. It clears stored records and relationships, indexes the files still present, and checks that the final record count matches.

  • Rebuild the index after deleting an ADR file
  • Remove stale relationships after editing an ADR
  • Reconcile the ADR index on a schedule
ruvnet/ruflo78.3KUpdated Oct 21, 2026

adr-review

FreeSummaryAI rating 80

Review code changes against accepted Architecture Decision Records, documents that capture agreed design choices. Report violations, outdated references, compliant changes, and areas without ADR coverage, then suggest code fixes or a new decision record where appropriate.

  • Check a pull request before merging
  • Review major code changes against agreed design decisions
  • Find references to superseded ADRs
ruvnet/ruflo78.3KUpdated Oct 21, 2026

adr-verify

FreeSummaryAI rating 90

Check saved architecture decision records (ADRs) for broken references, circular replacement relationships, and inconsistent statuses. Use the results to verify imported records or stop a CI check when selected integrity rules fail.

  • Checking ADR integrity after import
  • Blocking CI when ADR issues are found
  • Reviewing ADR data before a release
ruvnet/ruflo78.3KUpdated Oct 21, 2026

See all skills by ruvnet

Report a problem with this skill