trader-portfolio-cg
O que ela faz
Esta skill calcula os pesos de alocação de uma carteira usando um método matemático mais rápido chamado gradiente conjugado. Ela é para quem analisa como distribuir investimentos entre ativos, com os próprios dados.
Quando usar
- ✓Quando você quer pesos de carteira calculados a partir de uma matriz de covariância.
- ✓Quando o método de carteira mais antigo é lento demais para os seus dados.
- ✓Quando você quer comparar o método mais rápido com o mais antigo.
Link da skill
https://github.com/ruvnet/ruflo/blob/main/plugins/ruflo-neural-trader/skills/trader-portfolio-cg/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Calcule os pesos de média-variância para os meus cinco ativos usando o método mais rápido.”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
A skill resolve a equação da carteira pelo método do gradiente conjugado, registra qual método foi usado e recorre a um cálculo local se um caminho nativo falhar. Uma configuração pode desligar o caminho rápido para comparação.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do GitHub.
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:
Ensure neural-trader is available:
npm ls neural-trader 2>/dev/null || npm install --ignore-scripts neural-traderRead 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) andexpectedReturns: number[](length n).Solve Σ · x = μ via the SublinearAdapter (preferred path) when
RUFLO_NEURAL_TRADER_DISABLE_CGis 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__solveonglobalThis(and honoursRUFLO_SUBLINEAR_NATIVE=1as 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 readsresult.methodto 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 }Fallback (legacy Neumann) — if step 3 reports
degraded: true(non-SPD input, non-square matrix, MCP error) OR ifRUFLO_NEURAL_TRADER_DISABLE_CG=1:npx neural-trader --portfolio optimizeCapture the weights output and tag the artifact metadata with
method: 'neumann-fallback'and areasonfield.Store the optimal weights to
trading-risknamespace with full provenance metadata. Takemethodandsolverstraight 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,
Perguntas frequentes
Isso me diz o que comprar?
Ele calcula os pesos a partir dos dados que você fornece. A decisão sobre o que fazer é sua.
Como desligo o método mais rápido?
Uma configuração pode desativá-lo, o que volta ao método mais antigo para comparação.
E se os dados de covariância estiverem ruins?
O método assume uma matriz simétrica válida, então dados ruins podem comprometer os resultados.
Detalhes
Descrição original do autor
Mean-variance portfolio optimization via Conjugate Gradient — 40-60× faster than the legacy Neumann path (ADR-126 Phase 3, ADR-123 Wedge 8)
repo: ruvnet/ruflo
Popularidade
- Estrelas no GitHub
- 81 mil
- Posição no ranking
- #1670
- Licença
- MIT
- Atualizada em
- 02/11/2026
Comentários
- …
Mais skills deste repositório
agent-adaptive-coordinator
81 milAjuda seu agente a dividir e rebalancear um grupo de agentes de IA conforme a carga de trabalho muda, escolhendo um layout adequado à tarefa.
agent-agent
81 milEnsina seu agente a transformar um grande objetivo em um plano ordenado de ações e a replanejar quando as condições mudarem.
agent-agentic-payments
81 milAjuda seu agente a gerenciar mandatos de gasto para compras com IA, com tetos de valor, janelas de tempo, regras de lojistas e aprovações assinadas.
agent-analyze-code-quality
81 milAjuda seu agente a revisar código quanto à qualidade, encontrando code smells, dívida técnica e ideias de refatoração sem alterar os arquivos.
Skills parecidas
gitcrawl
394 milPermite que seu agente pesquise um arquivo salvo de issues e pull requests do GitHub, agrupe os duplicados e verifique o status atual deles no GitHub.
slacrawl
394 milPermite que seu agente pesquise e conte mensagens em um arquivo local do Slack, verifique quão atualizado ele está e o atualize quando necessário.
goplaces
394 milAjuda seu agente a buscar lugares, obter detalhes e avaliações e identificar nomes de lugares usando o Google Places, com saída em JSON para scripts.