Skip to content

Dicoangelo/frontier-alpha

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

133 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Frontier Alpha

Typing SVG

Metaventions AI Author Live Demo License


Tests Lines Files Endpoints Factors Version



React TypeScript Fastify Vite Supabase GPT-4o

AI-powered portfolio optimization with explainable recommendations and self-improving belief systems.


Core Philosophy

┌────────────────────────────────────────────────────────────────────────────────┐
│                                                                                │
│   ANALYZE           →          LEARN            →          EXPLAIN            │
│   80+ quantitative              from every                  every decision    │
│   factors                       episode                     in plain language  │
│                                                                                │
│   ══════════════════════════════════════════════════════════════════════════   │
│                                                                                │
│   • Institutional-grade quant          • Self-improving CVRF beliefs          │
│   • Beyond Fama-French 5              • Walk-forward backtesting             │
│   • Real-time streaming               • LLM + template explanations          │
│                                                                                │
└────────────────────────────────────────────────────────────────────────────────┘


System Architecture

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#00d9ff', 'primaryTextColor': '#fff', 'primaryBorderColor': '#00d9ff', 'lineColor': '#00d9ff', 'secondaryColor': '#1a1a2e', 'tertiaryColor': '#0d1117', 'clusterBkg': '#0d1117', 'clusterBorder': '#00d9ff'}}}%%
flowchart TB
    subgraph PLATFORM["FRONTIER ALPHA PLATFORM"]
        direction TB

        subgraph CLIENT["INTERFACE LAYER — React 19 + Vite 7"]
            direction LR
            PORTFOLIO["Portfolio\nDashboard\n━━━━━━━━━━\n58 Components\nZustand + RQ"]
            FACTORS["Factor\nExplorer\n━━━━━━━━━━\nRecharts + D3\nVisualizations"]
            EARNINGS["Earnings\nCalendar\n━━━━━━━━━━\nForecasts\nPositioning"]
            CVRF_UI["CVRF Beliefs\nVisualization\n━━━━━━━━━━\nEpisode History\nConviction Map"]
        end

        subgraph SERVER["INTELLIGENCE LAYER — Fastify 4 + Node 20"]
            direction LR
            FACTOR_ENGINE["Factor Engine\n━━━━━━━━━━\n80+ Factors\n6 Categories"]
            CVRF_CORE["CVRF Manager\n━━━━━━━━━━\nBelief Updater\nEpisode Learning"]
            ORACLE["Earnings Oracle\n━━━━━━━━━━\nBeat Rates\nExpected Moves"]
            EXPLAINER["Cognitive\nExplainer\n━━━━━━━━━━\nGPT-4o + Template\nConfidence Scores"]
        end

        subgraph ENGINES["COMPUTE LAYER"]
            direction LR
            OPTIMIZER["Monte Carlo\nOptimizer\n━━━━━━━━━━\nMax Sharpe\nMin Variance"]
            BACKTEST["Walk-Forward\nBacktest\n━━━━━━━━━━\nCVRF Integration\nHistorical Replay"]
            RISK["Risk Alert\nSystem\n━━━━━━━━━━\n11 Alert Types\nReal-time"]
        end

        subgraph DATA["DATA LAYER"]
            SUPABASE[("Supabase\nPostgreSQL + RLS\n━━━━━━━━━━\nReal-time Subs\n6 Migrations")]
            POLYGON["Polygon.io\n━━━━━━━━━━\nWebSocket Stream\nReal-time Quotes"]
            ALPHA["Alpha Vantage\n━━━━━━━━━━\nFundamentals\nKen French"]
        end
    end

    INVESTOR(("INVESTOR"))

    INVESTOR <==>|"Browser + PWA"| PORTFOLIO
    INVESTOR <==>|"Push Alerts"| RISK
    PORTFOLIO --> FACTOR_ENGINE
    FACTORS --> FACTOR_ENGINE
    EARNINGS --> ORACLE
    CVRF_UI --> CVRF_CORE
    FACTOR_ENGINE --> EXPLAINER
    CVRF_CORE --> OPTIMIZER
    CVRF_CORE --> BACKTEST
    ORACLE --> EXPLAINER
    OPTIMIZER --> RISK
    FACTOR_ENGINE -.->|"scores"| SUPABASE
    CVRF_CORE -.->|"beliefs"| SUPABASE
    FACTOR_ENGINE -.->|"quotes"| POLYGON
    ORACLE -.->|"fundamentals"| ALPHA

    style PLATFORM fill:#0d1117,stroke:#00d9ff,stroke-width:3px
    style CLIENT fill:#1a1a2e,stroke:#00d9ff,stroke-width:2px
    style SERVER fill:#1a1a2e,stroke:#9945ff,stroke-width:2px
    style ENGINES fill:#1a1a2e,stroke:#ffd700,stroke-width:2px
    style DATA fill:#16213e,stroke:#00d9ff,stroke-width:2px
    style INVESTOR fill:#00d9ff,stroke:#fff,stroke-width:2px,color:#0d1117
Loading

Layered architecture — Institutional-grade intelligence for retail investors



Modular Architecture

Every subsystem is a module — swap implementations with a config change, zero code changes.

75+ modules · 67 API routes · 205 tests · 22 subsystems · 10 migrations · Pluggable everything
Subsystem Module Ships with Extend
Factor Analysis FactorEngine 80+ factors across 6 categories (momentum, value, quality, volatility, size, sentiment), Fama-French + custom Custom factor plugins via factors/
CVRF Intelligence CVRFManager Belief updater, concept extractor, episode manager, persistent storage, conviction tracking Custom belief models via cvrf/
Cognitive Explainer ExplanationService GPT-4o + template dual-mode, confidence scores, source attribution Any OpenAI-compatible LLM
Portfolio Optimization PortfolioOptimizer Monte Carlo simulation, max Sharpe, min variance, risk parity, CVRF-weighted Custom objective functions
Backtesting WalkForwardEngine Walk-forward engine, CVRF integration, historical data loader, episode replay Custom strategies via backtest/
Earnings Oracle EarningsOracle Calendar, consensus estimates, beat rates, expected moves, historical reactions Custom data sources
Risk System RiskAlertSystem 11 alert types (drawdown, volatility, concentration, factor drift, stop loss, take profit + 5 more) Custom alert types
Market Data MarketDataProvider Polygon.io (WebSocket streaming), Alpha Vantage (fundamentals), Ken French Library Any data provider
Trading BrokerAdapter Alpaca (paper + live), order management, preview, market clock, position tracking Any broker API
Options GreeksCalculator Implied volatility surface, Greeks calculation, strategy builder, chain analysis Custom pricing models
ML Engine NeuralFactorModel Regime detection, factor attribution, neural models, training pipeline Custom models via ml/
Tax Optimization TaxLotTracker Lot tracking, loss harvesting, wash sale detection, efficient rebalancer, reporting Custom tax rules
SEC Monitoring SECFilingMonitor Edgar filings, real-time filing alerts, SEC document parsing Custom filing types
Sentiment SentimentAnalyzer News sentiment scoring, social signal processing Custom sentiment sources
Notifications PushService VAPID Web Push, SSE streaming, alert delivery, browser push Custom channels
Analytics PerformanceAttribution Return attribution, factor decomposition, Brinson-style analysis Custom attribution models
Cache RedisCache Redis-backed caching with LRU eviction Any cache backend
Auth AuthMiddleware JWT + API key authentication, Supabase Row Level Security, rate limiting Custom auth providers
Social SharingService Portfolio sharing, leaderboards, public profiles, social discovery Custom social features
Multi-Currency MultiCurrency Currency conversion, international market support Custom currency providers
Observability MetricsCollector Structured logging (Pino), performance metrics, error tracking Prometheus, OTel (planned)

Platform Support

  • Vercel — Serverless + static deployment (production)
  • Docker — Full-stack containerized (docker-compose.yml)
  • Railway — Auto-deploy from git (railway.toml)
  • Render — Alternative PaaS deployment (render.yaml)
  • Localnpm run dev:all (API port 3000, client port 5173)
  • 🚧 Python ML — Optional uvicorn engine (port 8000)

CVRF Engine (Full-Stack Belief System)

All custom, zero external ML dependencies — no scikit-learn, no TensorFlow, no framework lock-in:

Layer Implementation
Concept Extraction ConceptExtractor.ts — extract investment beliefs from factor analysis
Belief Management CVRFManager.ts — orchestrate belief lifecycle, conviction tracking
Reinforcement BeliefUpdater.ts — reinforce correct beliefs, weaken incorrect ones
Episode Tracking EpisodeManager.ts — temporal windows, regime change detection
Persistence PersistentCVRFManager.ts — Supabase-backed survival across restarts
Integration integration.ts — connect beliefs to optimizer and backtest runner

The system automatically learns, reinforces, and manages beliefs via episodes.

# CVRF Configuration
CVRF_LEARNING_RATE=0.1
CVRF_DECAY_RATE=0.05
CVRF_MIN_CONVICTION=0.1
CVRF_MAX_CONVICTION=1.0
CVRF_EPISODE_WINDOW=30

ML Pipeline (Neural Factor Intelligence)

Layer Implementation
Regime Detection RegimeDetector.ts — identify bull, bear, and transitional market regimes
Neural Factors NeuralFactorModel.ts — learned factor representations beyond Fama-French
Attribution FactorAttribution.ts — decompose returns into factor contributions
Training TrainingPipeline.ts — walk-forward training with out-of-sample validation
Python Bridge ml/main.py — optional uvicorn FastAPI engine for heavy compute
# ML Configuration
ML_ENGINE_URL=http://localhost:8000
ML_REGIME_LOOKBACK=252
ML_RETRAIN_INTERVAL=30

Client Architecture

Layer Implementation
Pages 19 views — Dashboard, Portfolio, Factors, CVRF, Earnings, Options, Tax, Trading, Backtest, ML, Social, Settings
Components 68 React 19 components across 18 domains (portfolio, charts, cvrf, trading, risk, earnings, options + more)
State 5 Zustand stores — portfolioStore, quotesStore, alertsStore, authStore, themeStore
Data Fetching React Query + custom hooks — useQuotes, useTrading, useNotifications + 6 more
Real-time WebSocket → SSE → Polling progressive fallback via wsClient
API Layer 7 typed API modules — client, cvrf, earnings, factors, portfolio, websocket + trading hooks
PWA Service Worker, Web Push API, offline caching, installable


Core Systems

Factor Engine

80+ Quantitative Factors

Six research-backed categories going beyond Fama-French 5: momentum, value, quality, volatility, size, sentiment, macro, and sector exposures.


FactorEngine.ts SentimentAnalyzer.ts


CVRF Intelligence

Self-Improving Belief System

Conceptual Verbal Reinforcement Framework. Learns episode-over-episode — reinforces correct beliefs, weakens incorrect ones. Investment convictions that evolve.


CVRFManager.ts BeliefUpdater.ts EpisodeManager.ts


Earnings Oracle

Forecast + Position + React

Calendar, consensus estimates, historical reactions, options-implied expected moves, beat rates, and pre/post-earnings positioning recommendations.


EarningsOracle.ts


Cognitive Explainer

GPT-4o + Template Dual-Mode

Every recommendation explained in plain language. LLM mode for rich narratives, template fallback for zero-API operation. Confidence scores and source attribution.


ExplanationService.ts CognitiveInsight.tsx


Portfolio Optimizer

Monte Carlo Simulation

Max Sharpe, min variance, and risk parity strategies. CVRF-integrated belief weighting. Walk-forward backtesting against real market history.


optimizer/ backtest/


Risk + Streaming

Real-time Market Intelligence

11 risk alert types (drawdown, volatility, concentration + 8 more). WebSocket → SSE → Polling fallback. Browser push notifications for earnings and risk events.


notifications/ trading/



Component Registry

Layer Component Description Tech Status
Interface 58 Components Portfolio, Factors, Earnings, CVRF, Risk, Options, Charts React 19, Tailwind Production
Intelligence Factor Engine 80+ factor exposures across 6 categories TypeScript v1.0.4
Intelligence CVRF Manager Episodic learning with belief persistence TypeScript, Supabase v1.0.4
Intelligence Earnings Oracle Forecasts, beat rates, expected moves TypeScript v1.0.4
Intelligence Cognitive Explainer GPT-4o + template dual-mode explanations OpenAI, TypeScript v1.0.4
Compute Portfolio Optimizer Monte Carlo, max Sharpe, min variance, risk parity TypeScript v1.0.4
Compute Walk-Forward Backtest CVRF-integrated historical replay TypeScript v1.0.4
Compute Risk Alert System 11 alert types, real-time monitoring TypeScript v1.0.4
Data Supabase PostgreSQL + RLS, real-time subscriptions Supabase Active
Data Polygon.io WebSocket real-time market data REST + WS Active
Data Alpha Vantage Fundamentals, earnings, Ken French Library REST Active


CVRF — Episodic Learning Engine

The belief system that learns from its own track record


┌──────────────────────────────────────────────────────────────────────────────────┐
│                       CVRF — EPISODIC LEARNING LOOP                              │
├──────────────────────────────────────────────────────────────────────────────────┤
│                                                                                   │
│  Episode N                                                                        │
│    │                                                                              │
│    ▼                                                                              │
│  [Concept Extractor] → Extract investment beliefs from factor analysis           │
│    │                                                                              │
│    ▼                                                                              │
│  [Belief Updater] → Compare predictions vs actual market outcomes                │
│    │                   Reinforce correct beliefs (↑ conviction)                   │
│    │                   Weaken incorrect beliefs  (↓ conviction)                   │
│    ▼                                                                              │
│  [Episode Manager] → Track performance across time windows                       │
│    │                   Detect market regime changes                               │
│    ▼                                                                              │
│  [Persistent CVRF] → Store beliefs in Supabase (survive restarts)                │
│    │                                                                              │
│    ▼                                                                              │
│  Episode N+1 → Better recommendations, stronger convictions                      │
│                                                                                   │
└──────────────────────────────────────────────────────────────────────────────────┘

Module File Purpose
Core CVRFManager.ts Belief management and update orchestration
Learning BeliefUpdater.ts Reinforcement learning on conviction strength
Extraction ConceptExtractor.ts Extract investment concepts from analysis
Episodes EpisodeManager.ts Track and compare episode performance
Persistence PersistentCVRFManager.ts Supabase storage layer
Integration integration.ts Connect to optimizer and backtest runner


Quick Start

# 1. Clone and install
git clone https://github.com/Dicoangelo/frontier-alpha.git
cd frontier-alpha && npm install && cd client && npm install && cd ..

# 2. Configure environment
cp .env.example .env
# Edit .env with your Polygon.io and Alpha Vantage API keys
# (optional — mock data works without them)

# 3. Start development
npm run dev:all

The client opens at http://localhost:5173 and the API at http://localhost:3000/api/v1/health.



API

Production API at https://frontier-alpha.metaventionsai.com

Endpoint Method Description
/api/v1/health GET Health check
/api/openapi GET OpenAPI specification
/api/v1/quotes/:symbol GET Real-time quote
/api/v1/portfolio/factors/:symbols GET Factor exposures
/api/v1/portfolio/optimize POST Portfolio optimization
/api/v1/earnings/forecast/:symbol GET Earnings forecast
/api/v1/cvrf/beliefs GET Current CVRF beliefs
Example Requests (click to expand)
# Real-time quote
curl https://frontier-alpha.metaventionsai.com/api/v1/quotes/AAPL

# Factor exposures
curl https://frontier-alpha.metaventionsai.com/api/v1/portfolio/factors/AAPL,NVDA,MSFT

# Optimize a portfolio
curl -X POST https://frontier-alpha.metaventionsai.com/api/v1/portfolio/optimize \
  -H "Content-Type: application/json" \
  -d '{"symbols": ["AAPL","NVDA","MSFT","GOOGL","AMZN"], "config": {"objective": "max_sharpe"}}'

# Earnings forecast
curl https://frontier-alpha.metaventionsai.com/api/v1/earnings/forecast/NVDA

# CVRF beliefs
curl https://frontier-alpha.metaventionsai.com/api/v1/cvrf/beliefs

See the full API Reference for all 29+ endpoints, request/response formats, and error codes.



Development

npm run dev:all          # Start API + client concurrently
npm run dev              # API server only (port 3000)
npm run client:dev       # Client only (port 5173)
npm test                 # Run server tests (watch mode)
npm run test:unit        # Server unit tests (single run)
npm run test:all         # All tests (server + client) — 205 total
npm run test:coverage    # Coverage report
npm run lint             # ESLint
npm run build            # Production build
npm run db:migrate       # Apply Supabase migrations
npm run ml:start         # Optional Python ML engine (port 8000)

Documentation

Document Description
API Reference Complete endpoint documentation with examples
User Guide End-user guide: features, workflows, PWA installation
Developer Guide Setup, architecture decisions, testing, deployment
Protocol Discovery and innovation protocol
Changelog Version history and feature log

Tech Stack

Layer Technology
Frontend React 19, Vite 7, TypeScript 5.3, Tailwind CSS, Zustand, React Query
Visualization Recharts, D3.js, Lucide Icons
Backend Node.js 20, Fastify 4, TypeScript 5.3, Zod validation
Database Supabase (PostgreSQL), Row Level Security, real-time subscriptions
Market Data Polygon.io (real-time quotes), Alpha Vantage (fundamentals + earnings)
Academic Data Ken French Library (academic factor returns)
AI GPT-4o (cognitive explanations)
Infrastructure Vercel (serverless + static), Docker, Railway, Sentry
Testing Vitest (205 tests), Testing Library, MSW (Mock Service Worker)
PWA Service Worker, Web Push API, offline caching


Roadmap

Phase 1 — Complete

  • Factor Engine (80+ factors across 6 categories)
  • Portfolio Optimizer (Monte Carlo, max Sharpe, min variance, risk parity)
  • CVRF Intelligence (episodic learning, belief persistence)
  • Cognitive Explainer (GPT-4o + template dual-mode)
  • Earnings Oracle (calendar, forecasts, historical reactions)
  • Walk-Forward Backtest (CVRF-integrated historical replay)
  • Risk Alert System (11 alert types, real-time monitoring)
  • Push Notifications (browser push for risk + earnings events)
  • PWA Support (installable, offline caching)
  • Real-time Streaming (WebSocket → SSE → Polling fallback)
  • Options Chain Analysis
  • Supabase Auth + RLS
  • Vercel Deployment + CI/CD

Phase 2 — Next

  • Social sentiment aggregation (X, Reddit, StockTwits)
  • Multi-portfolio management
  • Sector rotation signals
  • Advanced options strategies (spreads, iron condors)
  • Mobile companion app
  • Collaborative portfolios
  • Webhook integrations (Slack, Discord alerts)


Vision

╔══════════════════════════════════════════════════════════════════════════════╗
║                                                                              ║
║   "The best investment tools don't just analyze —                           ║
║    they learn, explain, and evolve with the market."                        ║
║                                                                              ║
║   ════════════════════════════════════════════════════════════════════════   ║
║                                                                              ║
║   FRONTIER ALPHA IS BUILDING TOWARD:                                         ║
║                                                                              ║
║   ▸ Every retail investor has institutional-grade intelligence               ║
║   ▸ Recommendations you can understand and verify                           ║
║   ▸ Belief systems that compound knowledge over time                        ║
║   ▸ AI that explains itself — never a black box                             ║
║                                                                              ║
║   ════════════════════════════════════════════════════════════════════════   ║
║                                                                              ║
║   "Let the invention be hidden in your vision."                              ║
║                                                                              ║
╚══════════════════════════════════════════════════════════════════════════════╝


Contact


Channel Link
Website metaventionsai.com
GitHub @Dicoangelo
Twitter @dicoangelo
Email dicoangelo@metaventionsai.com



Part of the Antigravity Ecosystem — Built by @dicoangelo


About

Cognitive Factor Intelligence Platform — AI-powered portfolio optimization with 80+ factors, episodic learning (CVRF), and explainable recommendations. Metaventions AI.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

Packages

 
 
 

Contributors