convez.ai
MCP ServerFinanceiroAvançado
Protocol-Wealth

Nexus Core — Motor de Análise Financeira Regime-Adaptativo

Protocol-Wealth/nexus-core

Engine de análise financeira com orquestração MCP para agentes de IA

Ver no GitHub
BomPluginScore · de 0 a 100

MCP server open source que expõe análise financeira e dados de mercado via Protocol Context Protocol e REST API pública. Construído em FastAPI + FastMCP para qualquer cliente MCP-compatível (Claude, GPT, Gemini) acessar lógica de regime-aware sem implementar domínio financeiro. Roda em produção com mypy strict + ruff, hospedado no Google Cloud Run.

Instalação

$npx convez-ai Protocol-Wealth/nexus-core

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
5
Forks
2
Acompanhando
1
Saúde
87%
Último commit
há 6 dias
Versão
v1.0.3
Issues abertas
10
Contribuidores
3

Casos de uso

  • Integrar análise financeira regime-aware em agentes Claude/GPT
  • Construir ferramentas de planejamento financeiro sem reimplementar lógica de domínio
  • Acessar dados de mercado e classificação de regimes via API pública

Veredito

Solução robusta e auditável para casos de uso financeiro real; produzida por RIA registrada na SEC. Exige implementação própria de PII controls, autenticação e validação antes de uso com dados sensíveis — não é produto plug-and-play, mas framework educacional sólido.

README

A tradução para o português deste README ainda está na fila.

Nexus Core

Open source regime-adaptive financial analysis engine with MCP tool orchestration.

License Patent Pending OIN Member Python 3.12+ Contributions welcome GitHub stars

Live: nexusmcp.site | Source: GitHub | Patent: USPTO #64/034,229

Status

This is a reference framework and a starting point, not a production-ready product. It is a work in progress under active, iterative development.

Adopters are responsible for adding their own PII controls, access control, input validation, authentication, and data-handling boundaries appropriate to their own regulatory and security context before any real or sensitive data touches it. Adopters are also responsible for their own AI-provider data-handling posture; the framework makes no data-retention guarantees.

Provided as-is under Apache-2.0. Educational use only — nothing here is investment advice.

What This Is

Nexus Core is the open source foundation of the Protocol Wealth research engine — a regime-aware financial-analysis and DeFi/market-data engine that exposes its capabilities as a public, read-only REST API and as MCP (Model Context Protocol) tools. Any MCP-compatible AI client (Claude, GPT, Gemini) can access regime-aware analysis without implementing financial domain logic. It is built on FastAPI + FastMCP (Python 3.12, sync httpx, asyncpg), runs mypy --strict + ruff, and is deployed on Google Cloud Run behind Cloudflare at nexusmcp.site.

Built and tested in production by an SEC-registered RIA (Protocol Wealth LLC, CRD #335298).

Public API

The deployed surface is public, read-only, and carries no client data and no authentication. Every external integration degrades gracefully — to None, an empty result, or 503 — when its API key is absent.

Meta

EndpointDescription
GET /Landing page
GET /healthLiveness probe (rate-limit exempt)
GET /health/dbDatabase connectivity probe
GET /docsInteractive OpenAPI / Swagger UI
GET /mcp-guide · GET /llms.txtMCP client setup guide · agent site map (llmstxt.org)
GET /.well-known/security.txtRFC 9116 disclosure pointer
GET /api/usageProvider usage / quota report
POST /mcpModel Context Protocol over HTTP (FastMCP, also stdio). tools/list = research tools + health/describe/get_quotes + 19 planning tools (incl. the composite Roth/IRMAA trio); all read-only
GET /mcp/tools · POST /mcp/tools/{id}Planning REST gateway (pwplan-core, contractVersion 0.1.0, PII-free)

Regime & Scoring

EndpointDescription
GET /api/regimeEMF regime classification
GET /api/regime/signalsRaw regime signal readings
GET /api/score/{ticker}8-check EMF durability score (SEC EDGAR fundamentals)

Market & Economic Data

EndpointDescription
GET /api/market/quote/{symbol}Latest quote (yfinance/MBOUM/MarketStack/CoinGecko composite)
GET /api/market/history/{symbol}OHLCV price history
GET /api/economic/{series_id}FRED economic series

Options (educational)

EndpointDescription
GET /api/options/priceBlack-Scholes price + Greeks
GET /api/options/overlay/covered-callCovered-call overlay illustration
GET /api/options/overlay/cash-secured-putCash-secured-put overlay illustration
GET /api/options/overlay/collarProtective-collar overlay illustration
GET /api/options/crypto/currenciesCrypto option underliers + settlement model (Deribit)
GET /api/options/crypto/{currency}/instrumentsDeribit crypto options — BTC/ETH (inverse) + SOL/XRP/TRX/AVAX (USDC-linear)
GET /api/options/crypto/instrument/{instrument_name}Deribit crypto option detail
GET /api/options/crypto/{currency}/protective-putSettlement-aware protective-put floor (cost of protection)
GET /api/options/crypto/{currency}/collarSettlement-aware protective collar (put floor + financing call)
GET /api/options/crypto/{currency}/covered-callSettlement-aware covered-call overwrite illustration (coin yield)
GET /api/options/crypto/{currency}/covered-call-chainRank live OTM calls by annualized covered-call yield
GET /api/options/crypto/{currency}/regime-overwriteCovered-call strike tilted by the LIVE EMF macro regime
GET /api/options/crypto/{currency}/iv-term-structureNear-ATM implied-vol curve across tenors (which expiry pays richest)
GET /api/options/crypto/{currency}/vol-skewCall-side IV + vega by strike (which strike is richest to write)
POST /api/options/crypto/{currency}/ladderCalendar/strike covered-call ladder (coverage, blended yield)
POST /api/options/crypto/{currency}/rollRoll a short call (up/out net-credit economics)
POST /api/options/crypto/{currency}/book/mtmMark an options book + aggregate Greeks
POST /api/options/crypto/{currency}/book/scenarioSpot×IV stress grid + assignment flags

On-Chain & DeFi

EndpointDescription
GET /api/wallet/{address}Anonymous EVM wallet balance (DeBank)
GET /api/chain/chainsSupported chains
GET /api/chain/balance/{chain}/{address}Multi-chain native balance (Tatum)
GET /api/chain/native/{address}Native balance lookup
GET /api/vaultsDeFi vault discovery (vaults.fyi v2)
GET /api/vaults/chainsVault-supported chains
GET /api/solana/price/{mint}Solana SPL token USD price (Jupiter, keyless)
GET /api/solana/prices?mints=Batch Solana SPL token USD prices (Jupiter, keyless)

LP Analytics (Uniswap V3 + Aerodrome Slipstream)

EndpointDescription
GET /api/lp/chainsChains/versions with LP analytics
GET /api/lp/uniswap-v3/{chain}/{token_id}/analyticsPosition value, in-range status, exact impermanent-loss-vs-HODL, fee-APR estimate, uncollected fees, Merkl reward APR → total APR (USD prices required as query params)
GET /api/lp/uniswap-v3/{chain}/{token_id}/vs-benchmarkPosition return vs. hold-strategy benchmark returns over a window (USD prices required as query params)
GET /api/lp/aerodrome/{token_id}/analyticsAerodrome Slipstream position on Base, read on-chain (RPC) — value, in-range, token amounts, uncollected fees (USD prices required as query params). IL, fee APR, and AERO gauge APR are not available in on-chain-only mode (reported null/zero)

Supported chains (Uniswap V3): ethereum, base, optimism, polygon. (Arbitrum's published subgraph uses an incompatible schema and is not supported.) Aerodrome Slipstream — a Uniswap-V3 CLMM sibling — is read directly on-chain on Base, so the same pure engine drives it with no subgraph dependency.

Benchmarks

EndpointDescription
GET /api/benchmarksBase-100 buy-and-hold benchmark returns (BTC/ETH/SOL + ETH-USDC 50/50,60/40,70/30 + ETH-BTC 50/50)
GET /api/benchmarks/series?days=On-demand series from CoinGecko
GET /api/benchmarks/history?days=Series from persisted daily snapshots

Architecture

MCP Client (Claude, GPT, Gemini)  /  REST clients
    │ JSON-RPC over HTTP          │ HTTP
    ▼                             ▼
Nexus Core (FastAPI + FastMCP)
├── Regime Engine (engine/regime)
│   ├── Core signals: Gold/SPX vs 200WMA, real rates, DXY, VIX, credit spreads (BBB OAS)
│   ├── Supplementary: yield curve (2s10s), precious metals
│   └── 5 regime states (Growth, Transition, Hard Asset, Deflation, Repression)
├── EMF Scoring (engine/scoring/emf)
│   └── 8-check durability scoring + confidence tiers (SEC EDGAR fundamentals)
├── Options Pricing (engine/pricing)
│   └── Black-Scholes price + Greeks, covered-call/CSP/collar overlays
├── LP Analytics (engine/lp/uniswap_v3.py)
│   └── Pure CLMM math: tick math, get_amounts_for_liquidity, exact IL, fee APR
│       (protocol-agnostic — reused across ethereum/base/optimism/polygon)
├── Benchmarks (engine/benchmarks.py)
│   └── Base-100 buy-and-hold compositions
├── Data Clients (data/)
│   ├── market/   yfinance, MBOUM, MarketStack, CoinGecko + cache + composite
│   ├── macro/    FRED, EIA, BEA, Treasury
│   ├── edgar/    SEC fundamentals (XBRL)
│   ├── derivatives/  Deribit
│   └── onchain/  DeBank, Tatum, The Graph, Merkl, vaults.fyi, DefiLlama, Jupiter
├── Persistence (data/db.py, data/snapshots.py)
│   └── asyncpg → private Cloud SQL (daily benchmark snapshots)
├── Jobs (jobs/daily_snapshot.py)
└── MCP Tool Registry (mcp/server)
    ├── @mcp.tool() decorator pattern
    └── Pluggable ResponseFilter hooks (adopter-supplied auth / PII / audit)

See docs/ARCHITECTURE.md for the signal ensemble, regime-state table, 8-check definitions, and the ResponseFilter tiering hook.

Key Innovations

Regime Detection — Signal ensemble maps macroeconomic conditions to regime states, informing asset-specific analysis.

EMF Scoring — Multi-dimensional 8-check durability assessment combining fundamentals, technicals, momentum, and regime alignment.

Exact LP Analytics — Pure constant-liquidity-market-maker math computes exact impermanent-loss-vs-HODL, fee APR, and total APR (including Merkl rewards) for Uniswap V3 positions.

MCP Orchestration — Tools auto-adjust analysis based on detected regime. Any LLM accesses regime-aware insights without domain logic.

Built on the Shoulders of Giants

Nexus Core stands on a foundation of exceptional open-source projects. We bundle or extend these libraries with full attribution — see NOTICE and THIRD_PARTY_LICENSES.md for complete legal notices.

Portfolio Optimization & Risk Analytics

  • PyPortfolioOpt (MIT) — Mean-variance, Black-Litterman, HRP
  • Riskfolio-Lib (BSD-3) — 24 convex risk measures, factor models
  • empyrical-reloaded (Apache 2.0) — Performance metrics (Sharpe, Sortino, VaR)
  • pyfolio-reloaded (Apache 2.0) — Professional tear sheets
  • skfolio (BSD-3) — scikit-learn portfolio optimization
  • ffn (MIT) — Pandas financial functions

Derivatives Pricing & Fixed Income

  • QuantLib (Modified BSD) — Derivative pricing, yield curves
  • FinancePy (MIT) — Numba JIT pricing for bonds/swaps/options

SEC EDGAR & Financial Data

  • edgartools (MIT) — SEC filings as Python objects + built-in MCP server
  • Arelle (Apache 2.0) — SEC-certified XBRL validation
  • sec-parser (MIT) — Semantic parsing for LLM pipelines
  • sec-edgar-downloader (MIT) — Bulk filing downloads
  • yfinance (Apache 2.0) — Market data

Backtesting & Factor Analysis

AI & ML for Finance

  • FinRL (MIT) — Reinforcement learning for portfolios
  • FinBERT (Apache 2.0) — Financial sentiment classification (via Transformers)

Huge thanks to every maintainer and contributor of these projects. Financial software has historically been locked behind proprietary walls — Nexus Core would not exist without the open-source financial ecosystem.

What's Open vs Private

Open (Apache 2.0): Framework architecture, scoring structure, layer model, tool pattern, the public REST/MCP surface, caching patterns — and Protocol Wealth's calibrated regime thresholds + scoring values, which PW publishes openly as part of the EMF framework (protocolwealthllc.com/framework). All third-party integrations listed above.

Private: API keys, client data, advisory/planning surfaces, the narrative/research pipeline, and any client-specific or suitability logic. (Calibrations are not private — EMF is a published framework. Adopters with different signal sources should still re-fit.)

Installation

Install from the source repository. A Protocol Wealth–controlled distribution is not yet published to PyPI — the bare nexus-core name on PyPI is not ours — so until a controlled distribution is published, install directly from this repository (the git-pinned form below).

Full install (all capabilities)

pip install "nexus-core[all] @ git+https://github.com/Protocol-Wealth/nexus-core.git"

Modular installs (reduce dep footprint)

Swap [all] for any single extra: serve (the public HTTP API + MCP server, nexusmcp.site) · mcp (local stdio MCP server) · optimization (PyPortfolioOpt, Riskfolio, skfolio) · risk (empyrical, pyfolio, ffn) · pricing (QuantLib, FinancePy) · edgar (edgartools, Arelle, sec-parser) · market (yfinance) · ai (FinRL, Transformers, torch — heavy) · backtest (zipline-reloaded, alphalens). Omit the bracket entirely for core only (regime + scoring).

pip install "nexus-core[serve] @ git+https://github.com/Protocol-Wealth/nexus-core.git"

From source

git clone https://github.com/Protocol-Wealth/nexus-core.git
cd nexus-core
pip install -e ".[all]"

Quick Start

Hosted — no install. The server is live at nexusmcp.site:

curl https://nexusmcp.site/health
curl https://nexusmcp.site/api/regime          # current macro regime
curl https://nexusmcp.site/mcp/tools            # planning contract + tool ids

# a planning tool (educational, PII-free — send age, never date of birth)
curl -X POST https://nexusmcp.site/mcp/tools/glide_path \
  -H 'Content-Type: application/json' \
  -d '{"currentAge": 40, "retirementAge": 65, "horizonAge": 95,
       "startEquityWeight": 0.8, "endEquityWeight": 0.4, "shape": "linear"}'

In Python — the regime engine is built over data providers:

from nexus_core.app.main import build_market_provider
from nexus_core.data.macro import FredMacroData
from nexus_core.engine.regime import RegimeEngine

engine = RegimeEngine(market_data=build_market_provider(), macro_data=FredMacroData())
result = engine.classify()
print(result.to_dict())   # regime code, confidence, per-signal breakdown, rationale

See examples/ for more runnable snippets.

Run the public API + MCP server

pip install -e ".[serve]"
nexus-core serve     # HTTP API + MCP-over-HTTP — http://127.0.0.1:8080
nexus-core mcp       # MCP server over stdio (for Claude Desktop)
nexus-core snapshot  # Write a daily benchmark snapshot to the database

nexus-core serve hosts the public surface deployed at nexusmcp.site: the read-only REST API described above, interactive docs at /docs, and an MCP endpoint at /mcp. See DEPLOY.md for the Cloud Run + Cloud SQL + Cloud Scheduler deployment.

Using with any MCP client

The hosted MCP endpoint is public and read-only, so any MCP-compatible AI client (Claude, GPT, Gemini), or an agent platform such as SmythOS, can register https://nexusmcp.site/mcp as a read-only MCP server — no account, no API key, no auth. For example, in a .mcp.json (or any client config that follows the same shape):

{
  "mcpServers": {
    "nexus-core": {
      "type": "http",
      "url": "https://nexusmcp.site/mcp"
    }
  }
}

See the MCP setup guide for per-client steps (Claude.ai, Claude Code, Claude Desktop, and other clients) and tools/list output.

Configuration

All configuration is environment-driven. Every variable is optional; the app runs without any of them, with reduced data coverage.

VariableEffect
FRED_API_KEYEnables /api/economic/* and macro precision for /api/regime
MBOUM_API_KEYAdds MBOUM as a market-data fallback
MARKETSTACK_API_KEYAdds MarketStack as a market-data fallback
COINGECKO_API_KEYRaises CoinGecko rate limits (works keyless too)
EIA_API_KEYEIA energy / commodity macro data
BEA_API_KEYBureau of Economic Analysis macro data
DEBANK_API_KEYEnables /api/wallet (DeBank)
TATUM_API_KEYEnables /api/chain and LP uncollected-fee lookups
VAULTSFYI_API_KEYEnables /api/vaults (vaults.fyi)
THEGRAPH_API_KEYEnables /api/lp (The Graph)
DATABASE_URLPersistence + /api/benchmarks/history (503 when unset)
NEXUS_RATE_LIMIT_PER_MINPer-IP request budget (default 60)
NEXUS_CORS_ORIGINSComma-separated CORS allow-list (default *)

Tech Stack

Python 3.12 · FastAPI · FastMCP · httpx · asyncpg · PostgreSQL (Cloud SQL) · Redis · pandas · numpy · scipy · mypy --strict · ruff · CI-gated test + lint suite

Documentation

Patent & IP

Patent Pending — USPTO Application #64/034,229 "Compliance-First Quantitative Research Engine with Multi-Signal Regime Detection, Systematic Asset Scoring, and AI Tool Orchestration via Model Context Protocol for SEC/FINRA-Regulated Financial Advisory Services"

This patent was filed defensively under Apache 2.0. The intent is to establish formal prior art and prevent third parties from patenting these concepts and restricting their use by independent financial advisors. Under Apache 2.0, you receive an automatic, perpetual, royalty-free patent grant. If you sue Protocol Wealth for patent infringement related to this software, your license terminates automatically.

Open Invention Network (OIN) Member — Protocol Wealth LLC is a member of the Open Invention Network (OIN), the world's largest patent non-aggression network with 4,100+ members including Google, IBM, Toyota, Meta, Microsoft, and Amazon. Learn more

See PATENTS for full non-assertion pledge.

License

Apache License 2.0 — see LICENSE.

Apache 2.0 includes an explicit patent retaliation clause that MIT lacks. If someone sues you for patent infringement related to Nexus, their right to use the software terminates automatically.

Third-party components retain their original licenses. See NOTICE and THIRD_PARTY_LICENSES.md.

Contributing

We welcome contributions. All commits must include a Signed-off-by: line certifying agreement with the Developer Certificate of Origin:

git commit -s -m "feat: your change"

See CONTRIBUTING.md for full guidelines.

Related

Links


Built by Protocol Wealth LLC — SEC-Registered Investment Adviser (CRD #335298)

Ver o original no GitHub

Bom para

Relacionados