Back to Case Studies
Data EngineeringDagsterDuckDBPolarsPythonFastAPIPlatform EngineeringReactLLMOps

Portfolio Analytics Platform

An internal quantitative research and capital allocation platform combining point-in-time lakehouse pipelines, stateless multi-factor scoring, and asymmetric LLM downside governance.

Context: An internal production platform engineered and operated at JPR Labs to run systematic multi-factor equity research, SEC EDGAR filing analysis, and monthly portfolio rebalancing on a single self-hosted Linux server.

Problem Statement

Running a systematic, factor-driven equity portfolio requires reconciling two distinct signals:

  1. Structured financial series (prices, corporate actions, quarterly income statements, balance sheets, cash flows) that must be adjusted for reporting lag to avoid look-ahead bias.
  2. Unstructured qualitative disclosures (10-K/10-Q footnotes, management capital allocation commentary, accounting risk factors) that standard quantitative ratios miss until margins already deteriorate.

Existing retail tools lack point-in-time accounting rigor and auditability, while institutional platforms (Bloomberg, FactSet, managed cloud warehouses) carry five-figure annual run rates. Furthermore, mixing discretionary qualitative reads with a systematic factor model usually fails in one of two ways: either discretionary conviction overrides the math whenever a narrative sounds compelling, or qualitative risks are ignored completely.

We built the Portfolio Analytics Platform (evolving our earlier QuantLens storage engine) to solve three engineering problems:

  1. Zero-cluster analytical speed: Process multi-year market and fundamental histories in seconds on a single NVMe node without Spark or managed warehouse overhead.
  2. Stateless, deterministic factor scoring: Guarantee identical scoring math across nightly batch pipelines and interactive UI weight simulations.
  3. Asymmetric LLM governance: Integrate LLM-parsed SEC filing reviews into position sizing under a strict mathematical invariant: qualitative verdicts can only cap or reduce a position's target weight, never inflate it.

System Architecture

1. Local NVMe Medallion Lakehouse (DuckDB + Delta Lake + Dagster)

For datasets under 1 TB, distributed network storage and JVM cluster overhead introduce latency without adding capability. We co-locate storage and compute on a single self-hosted Hetzner Cloud VM (NVMe storage) provisioned via Ansible, using Delta Lake (delta-rs) on disk and DuckDB + Polars for vectorized in-process execution.

LayerStorage PathContents & Invariants
Bronze/data/bronze/<source>Immutable raw payloads from SEC EDGAR, market price feeds, and ECB FX rates.
Silver/data/silver/<domain>Split-adjusted prices, currency-normalized financials, and point-in-time lagged fundamentals (enforcing filing publication dates rather than fiscal period ends).
Gold/data/gold/<mart>Denormalized instrument master, cross-sectional factor matrices, and portfolio drift snapshots synced to PostgreSQL for low-latency API serving.

TTL-Gated Orchestration: Pipelines are defined as Dagster software-defined assets with freshness policies and materialization metadata. Daily market runs check upstream asset timestamps and skip re-ingestion if the current trading day's snapshot is already materialized. Every run logs row counts, schema hashes, and upstream asset lineage so any historical portfolio snapshot can be reproduced bit-for-bit.

Disaster Recovery (RPO 24h / RTO < 15m): Because compute is single-node, durability is enforced through daily encrypted Delta Lake snapshots to S3-compatible object storage, idempotent Bronze-to-Gold recomputation, and full server reprovisioning via Ansible playbooks.


2. Stateless Multi-Factor Scoring Engine

The scoring logic lives in a standalone, stateless Python package (factor_engine) imported by both Dagster batch workers and the FastAPI backend. When an analyst adjusts factor weights in the UI and clicks Recalculate, FastAPI executes the exact same vectorized Polars expressions used in the nightly batch job.

The engine evaluates every universe constituent across four sleeves (defaulting to 30% Quality, 30% Value, 30% Growth, 10% Timing):

  • Quality (30%): Return on Invested Capital (ROIC), operating margin stability, net debt / EBITDA discipline.
  • Value (30%): Earnings yield, EBIT / EV, free cash flow yield.
  • Growth (30%): Trailing 12-month revenue growth YoY, forward EPS growth trajectory (preventing value traps where trailing multiples look cheap while fundamentals contract).
  • Timing (10%): Trend confirmation, drawdown recovery, and relative strength.

Continuous 4-Anchor Piecewise Scoring

Step-function grading creates artificial cliff edges where a 1 bps change in ROIC drops a holding from an A to a B. Pure cross-sectional z-scores distort when a single sector outlier skews the mean.

We combine sector-relative percentile ranks with a 4-anchor continuous piecewise linear curve (p10, p25, p50, p75, p90) mapped to a 0.0–10.0 scale:

# factor_engine/scoring/curves.py
import numpy as np
import polars as pl
 
ANCHOR_POINTS = np.array([0.0, 0.25, 0.50, 0.75, 1.0])
SCORE_POINTS  = np.array([0.0, 3.5,  6.0,  8.0,  10.0])
 
def score_metric_continuous(df: pl.DataFrame, metric_col: str, sector_col: str = "sector") -> pl.Series:
    """
    Computes sector-relative percentile rank and interpolates onto a continuous 0-10 score curve.
    Captures intermediate rank metadata for full UI auditability.
    """
    ranked = df.with_columns(
        (
            (pl.col(metric_col).rank(method="average").over(sector_col) - 1.0)
            / (pl.count(metric_col).over(sector_col) - 1.0).clip(lower_bound=1.0)
        ).alias("sector_pct_rank")
    )
    pct_values = ranked["sector_pct_rank"].to_numpy()
    return pl.Series(
        name=f"{metric_col}_score",
        values=np.interp(pct_values, ANCHOR_POINTS, SCORE_POINTS).round(2),
    )

Every score row persists its underlying inputs, peer group size, sector percentile, imputation flags, and letter grade (A through E) so the UI can render an exact trace for any holding.

Factor Engine dashboard showing Quality, Value, Growth, and Timing sleeve weights, continuous 0-10 scores, letter grades, and AI review multipliers


3. Asymmetric LLM Downside Governance

To incorporate qualitative filing analysis without allowing LLM hallucinations or narrative bias to manufacture long positions, the qualitative layer operates as a one-way downside risk gate.

Structured SEC Filing Evaluation

Dagster ingests 10-K and 10-Q filings from SEC EDGAR and runs them through a structured evaluation pipeline using Claude and Gemini across three forensic rubrics:

  1. Management Quality: Capital allocation track record, insider alignment, divergence between prior guidance and reported execution.
  2. Moat Durability: Pricing power, customer concentration shifts, emerging competitive substitution.
  3. Forensic Red Flags: Receivables growing faster than revenue, non-GAAP adjustment inflation, off-balance-sheet obligations, deteriorating free cash flow conversion.

Strict Downside-Only Schema & Expiry Contract

Every LLM review is validated against a strict Pydantic contract that maps the verdict to a deterministic position-sizing multiplier (1.0, 0.85, or 0.0) and enforces a 60-day staleness TTL:

# factor_engine/contracts/qualitative.py
from datetime import datetime, timedelta, timezone
from enum import Enum
from pydantic import BaseModel, Field, computed_field
 
class QualVerdict(str, Enum):
    CONFIRM = "CONFIRM"  # Thesis intact; full factor allocation permitted
    CAUTION = "CAUTION"  # Moderate concern; trims target weight by 15%
    VETO    = "VETO"     # Material thesis/accounting breach; blocks capital deployment
 
VERDICT_MULTIPLIERS: dict[QualVerdict, float] = {
    QualVerdict.CONFIRM: 1.00,
    QualVerdict.CAUTION: 0.85,
    QualVerdict.VETO:    0.00,
}
 
class FilingCitation(BaseModel):
    filing_accession: str = Field(description="SEC EDGAR accession number (e.g. 0000320193-26-000010)")
    section: str          = Field(description="Filing item or footnote reference (e.g. Item 7 MD&A, Note 12)")
    verbatim_quote: str   = Field(min_length=20)
 
class QualitativeReviewRecord(BaseModel):
    ticker: str
    verdict: QualVerdict
    summary_rationale: str
    citations: list[FilingCitation] = Field(min_length=1)
    reviewed_at: datetime
 
    @computed_field
    @property
    def sizing_multiplier(self) -> float:
        # Invariant: LLM review can never exceed 1.0x of the quantitative target weight
        return VERDICT_MULTIPLIERS[self.verdict]
 
    @computed_field
    @property
    def is_stale(self) -> bool:
        return datetime.now(timezone.utc) - self.reviewed_at > timedelta(days=60)

Because sizing_multiplier <= 1.0, an enthusiastic LLM review can never turn a low-scoring stock into a buy. Conversely, if the forensic pass flags a severe accounting or thesis break (VETO, multiplier 0.0), the allocation engine zeroes the target weight and flags the holding with trigger qual_veto (SELL) in the rebalancing queue. Reviews older than 60 days automatically mark is_stale = True, blocking automated allocation until re-verified against the latest filing.


4. Allocation Engine & Rebalancing Queue (FastAPI + React)

The allocation engine converts composite factor scores (Core Score) and qualitative multipliers into target portfolio weights across three portfolio buckets (Cash 5%, Core ETFs 40%, Active Single-Names 55%), subject to hard concentration caps (single-name maximums, sector caps, and minimum trade size thresholds):

raw_weight(ticker) = alloc_units(core_score) * sizing_multiplier(qual_verdict)

The React + TypeScript frontend (built with TanStack Router and TanStack Query) compares live holdings against target weights to compute portfolio drift and emit a prioritized action queue (BUY, SELL, TRIM, NEW, HOLD) with an audit trace (Explain) for every row:

  • Total Drift & Largest Gap Tracking: Surfaces immediate portfolio-level divergence (e.g., 16.4% total drift, -3.8% largest overweight gap on a qual_veto position).
  • Explicit Action Reasons: Every recommended trade records its primary driver (Qual veto, Factor rank, Score decay, Below target, Excess cash, or In target band).
  • One-Click JSON Export: Snapshots (Snapshot a3f8c12b) can be exported as structured JSON for execution logging and historical attribution.

Allocations Engine showing portfolio mix across Cash, Core, and Active buckets, sector drift bars, and the prioritized rebalancing trade queue


Unit Economics & Architecture Trade-Offs

LayerSelf-Hosted ImplementationManaged Enterprise EquivalentEngineering Rationale
OrchestrationDagster OSS (TTL-gated assets)Databricks Workflows / Managed AirflowFull asset lineage and type-checked Python pipelines with zero per-task orchestration fees.
Analytical ComputeDuckDB + Polars on local NVMeSpark Cluster / SnowflakeIn-memory vectorized scans over local Delta Lake tables complete in seconds with zero network shuffle.
Serving DatabaseSelf-hosted PostgreSQLAWS RDS / AuroraSub-10ms REST queries for the FastAPI backend and React dashboard.
Qualitative GovernanceClaude & Gemini APIs (batch-gated)Manual analyst coveragePay-per-filing inference (<€5/month) gated by 60-day TTL and strict citation schemas.
InfrastructureSingle Linux VPS + Ansible + S3 backupMulti-node cloud VPC<€20/month total infrastructure run rate with 15-minute Ansible RTO and daily off-site Delta snapshots.

Stack at a Glance

  • Data Lakehouse & Compute: DuckDB, Polars, Delta Lake (delta-rs), Dagster (Software-Defined Assets)
  • Backend & Scoring Engine: Python, FastAPI, Pydantic v2, SQLModel, asyncpg, PostgreSQL
  • Frontend: React 19, TypeScript, TanStack Router, TanStack Query, Tailwind CSS
  • LLM Governance: Anthropic Claude API, Google Gemini API (structured outputs with citation & TTL enforcement)
  • Infrastructure: Hetzner Cloud NVMe VPS, Docker, Ansible IaC, S3-compatible object storage backups

— Pedro

Founder & Principal Engineer