Skip to content

Protocol-Wealth/nexus-core

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

138 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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

Endpoint Description
GET / Landing page
GET /health Liveness probe (rate-limit exempt)
GET /health/db Database connectivity probe
GET /docs Interactive OpenAPI / Swagger UI
GET /mcp-guide · GET /llms.txt MCP client setup guide · agent site map (llmstxt.org)
GET /.well-known/security.txt RFC 9116 disclosure pointer
GET /api/usage Provider usage / quota report
POST /mcp Model 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

Endpoint Description
GET /api/regime EMF regime classification
GET /api/regime/signals Raw regime signal readings
GET /api/score/{ticker} 8-check EMF durability score (SEC EDGAR fundamentals)

Market & Economic Data

Endpoint Description
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)

Endpoint Description
GET /api/options/price Black-Scholes price + Greeks
GET /api/options/overlay/covered-call Covered-call overlay illustration
GET /api/options/overlay/cash-secured-put Cash-secured-put overlay illustration
GET /api/options/overlay/collar Protective-collar overlay illustration
GET /api/options/crypto/currencies Crypto option underliers + settlement model (Deribit)
GET /api/options/crypto/{currency}/instruments Deribit 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-put Settlement-aware protective-put floor (cost of protection)
GET /api/options/crypto/{currency}/collar Settlement-aware protective collar (put floor + financing call)
GET /api/options/crypto/{currency}/covered-call Settlement-aware covered-call overwrite illustration (coin yield)
GET /api/options/crypto/{currency}/covered-call-chain Rank live OTM calls by annualized covered-call yield
GET /api/options/crypto/{currency}/regime-overwrite Covered-call strike tilted by the LIVE EMF macro regime
GET /api/options/crypto/{currency}/iv-term-structure Near-ATM implied-vol curve across tenors (which expiry pays richest)
GET /api/options/crypto/{currency}/vol-skew Call-side IV + vega by strike (which strike is richest to write)
POST /api/options/crypto/{currency}/ladder Calendar/strike covered-call ladder (coverage, blended yield)
POST /api/options/crypto/{currency}/roll Roll a short call (up/out net-credit economics)
POST /api/options/crypto/{currency}/book/mtm Mark an options book + aggregate Greeks
POST /api/options/crypto/{currency}/book/scenario Spot×IV stress grid + assignment flags

On-Chain & DeFi

Endpoint Description
GET /api/wallet/{address} Anonymous EVM wallet balance (DeBank)
GET /api/chain/chains Supported chains
GET /api/chain/balance/{chain}/{address} Multi-chain native balance (Tatum)
GET /api/chain/native/{address} Native balance lookup
GET /api/vaults DeFi vault discovery (vaults.fyi v2)
GET /api/vaults/chains Vault-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)

Endpoint Description
GET /api/lp/chains Chains/versions with LP analytics
GET /api/lp/uniswap-v3/{chain}/{token_id}/analytics Position 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-benchmark Position return vs. hold-strategy benchmark returns over a window (USD prices required as query params)
GET /api/lp/aerodrome/{token_id}/analytics Aerodrome 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

Endpoint Description
GET /api/benchmarks Base-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

Full install (all capabilities)

pip install nexus-core[all]

Modular installs (reduce dep footprint)

pip install nexus-core                    # Core only (regime, scoring)
pip install nexus-core[serve]             # + the public HTTP API + MCP server (nexusmcp.site)
pip install nexus-core[optimization]      # + PyPortfolioOpt, Riskfolio, skfolio
pip install nexus-core[risk]              # + empyrical, pyfolio, ffn
pip install nexus-core[pricing]           # + QuantLib, FinancePy
pip install nexus-core[edgar]             # + edgartools, Arelle, sec-parser
pip install nexus-core[market]            # + yfinance
pip install nexus-core[ai]                # + FinRL, Transformers, torch (heavy)
pip install nexus-core[backtest]          # + zipline-reloaded, alphalens

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.

Variable Effect
FRED_API_KEY Enables /api/economic/* and macro precision for /api/regime
MBOUM_API_KEY Adds MBOUM as a market-data fallback
MARKETSTACK_API_KEY Adds MarketStack as a market-data fallback
COINGECKO_API_KEY Raises CoinGecko rate limits (works keyless too)
EIA_API_KEY EIA energy / commodity macro data
BEA_API_KEY Bureau of Economic Analysis macro data
DEBANK_API_KEY Enables /api/wallet (DeBank)
TATUM_API_KEY Enables /api/chain and LP uncollected-fee lookups
VAULTSFYI_API_KEY Enables /api/vaults (vaults.fyi)
THEGRAPH_API_KEY Enables /api/lp (The Graph)
DATABASE_URL Persistence + /api/benchmarks/history (503 when unset)
NEXUS_RATE_LIMIT_PER_MIN Per-IP request budget (default 60)
NEXUS_CORS_ORIGINS Comma-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)

About

Open source regime-adaptive financial analysis engine with MCP tool orchestration. Apache 2.0 licensed with defensive patent grant.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors