<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Thomas Tarler on Medium]]></title>
        <description><![CDATA[Stories by Thomas Tarler on Medium]]></description>
        <link>https://medium.com/@ttarler?source=rss-4389f5a6ff54------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KUB6eF4qFQRNUHceoZeAsg.jpeg</url>
            <title>Stories by Thomas Tarler on Medium</title>
            <link>https://medium.com/@ttarler?source=rss-4389f5a6ff54------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:55:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ttarler/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[One Developer, 12 Workflows, and a Production ML System]]></title>
            <link>https://medium.com/@ttarler/one-developer-12-workflows-and-a-production-ml-system-fd934f7dae08?source=rss-4389f5a6ff54------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd934f7dae08</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[automated-trading]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Thomas Tarler]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 13:56:41 GMT</pubDate>
            <atom:updated>2026-03-17T13:56:41.833Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Sunday Night that Explains Everything</h3><p>It’s Sunday at 8 PM ET. The weekly calibration fires: 6 prescreening models retrain on SageMaker, isotonic regression recalibrates confidence scores, and Monte Carlo parameter tuning runs 500 Latin Hypercube samples against the last 28 days of trades. By 10 PM, a new parameter set clears all 5 guardrail gates and writes to the database.</p><p>Monday at 6:45 AM, the automated health check runs. It flags a P2: one prescreening endpoint is returning stale predictions — the calibration retraining job succeeded, but the endpoint didn’t pick up the new model artifact. A GitHub Issue is created with the ml-pipeline and P2-medium labels, filed under the Platform Maturity milestone. I open the issue, read the diagnostics the health check already gathered, push a one-line fix, and watch CI deploy it via blue-green before market open at 9:30.</p><p>One person. No pager. No Slack channel. No standup.</p><p>The question I get asked most: how does a solo data scientist run a production ML trading system — 9-stage pipeline, 6 prescreening endpoints, an RL ensemble (PPO + SAC + TD3), and 33 tunable execution parameters — without burning out or burning money?</p><p>The answer isn’t heroics. It’s systems. The rest of this post is the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zbnLZQ0mo6DWNavU" /></figure><p><em>The feedback loop: AI agents detect issues → create GitHub Issues → drive fixes through CI/CD → verify deployment. Under 10 minutes end to end.</em></p><p>I don’t have a team. I have a CLAUDE.md file with 13 policies, each one written in the blood of a past failure.</p><p>This file loads automatically at the start of every AI agent session. It’s institutional memory that never forgets. The $78,947 loss from Post 6? That produced policies 3, 6, and 7. The Ray segfault that cost 5 hours? Policy 6. Every expensive lesson is encoded as a rule the agent must follow.</p><p>But CLAUDE.md is just the constitution. The agents also have specialized roles, defined as skills:</p><p><strong>trading-health</strong> runs intraday diagnostics: checks all 6 prescreening endpoints, verifies the RL endpoint exists during market hours, validates that execution parameters loaded correctly, reviews open positions against risk limits. When it finds something wrong, it doesn&#39;t just report - it creates a GitHub Issue with the right priority label, checks for duplicates first, and includes the diagnostic output so I can act without re-investigating.</p><p><strong>daily-report</strong> produces a 16-section end-of-day analysis: P&amp;L decomposition by strategy, benchmark comparison against SPY/IWM/QQQ, position-level attribution, fill quality analysis, and risk metric summary. Every finding becomes a tracked issue.</p><p>The feedback loop is the real multiplier. Trading-health detects an issue at 6:45 AM. It creates a GitHub Issue with priority label and diagnostic context. I (or an agent) pick up the issue, write a fix, push to a branch. CI runs tests in parallel — 3 to 5 minutes. The fix merges and deploys via blue-green — another 2 minutes. The next trading-health run at market open verifies the fix is live by checking the deployment timestamp against merged PRs. It won’t blame code that wasn’t deployed yet.</p><p>That last detail matters. The health check cross-references PR merge times against ECS deployment timestamps. If a bug existed before the latest deploy, it reports it. If the fix merged but hasn’t deployed yet, it waits. This prevents the maddening false-positive cycle where monitoring fires on issues you’ve already fixed.</p><p>I also run multiple agents in parallel using git worktrees — each agent gets an isolated copy of the repository on its own branch. One agent investigates a P1 while another implements a feature on a separate branch. No merge conflicts, no context switching. The worktrees are disposable; the branches are the output.</p><p>The key insight is that CLAUDE.md makes every agent session start with full context. A new agent doesn&#39;t need onboarding - it reads the 13 policies, the directory rules, the mode detection table, and the deployment process. It knows not to put Ray imports in inference containers (policy 6, from the 5-hour segfault). It knows to verify deployments with logs, not just &quot;it returned 200&quot; (policy 3, from the $78,947 loss). The institutional memory is in the file, not in anyone&#39;s head.</p><p>Every software team has issue tracking. What’s unusual here is that the issues are mostly created by agents, not humans.</p><p>The system uses GitHub Issues with a structured label taxonomy:</p><ul><li><strong>Priority</strong>: P0-critical (system down) through P3-low (tech debt)</li><li><strong>Category</strong>: ml-pipeline, execution-engine, infrastructure, observability, security, testing, tech-debt</li><li><strong>Source</strong>: source:trading-health, source:daily-report, or manual</li></ul><p>Four milestones organize the backlog: Go-Live Blockers, Production Hardening, Platform Maturity, Feature Roadmap. P0s go to Go-Live Blockers. P3s go to Feature Roadmap. No ambiguity.</p><p>The P1 rule came from a real incident: a bug that blocked all buy orders was labeled P2 because the system was “still running.” Still running, but not trading. Now the policy is explicit — anything that blocks trades from executing is P1 minimum, never P2.</p><p>Automated issue creation covers all severity levels. Trading-health and daily-report create issues for P0 through P3 findings. Before creating an issue, they search existing open issues with matching source labels to avoid duplicates. If a matching issue exists, they add a comment with the new timestamp and context instead.</p><p>This replaces the team standup. Every morning, the trading-health run <em>is</em> the standup. Open issues sorted by priority tell me what to work on today. No status meeting, no “what are you working on?” — just a prioritized list generated by a system that checked everything 15 minutes ago.</p><p>The numbers tell the story: over 6 weeks, trading-health and daily-report have created or updated over 100 issues. About 70% were P2 or P3 — things that wouldn’t have caused immediate harm but would have accumulated into technical debt. The remaining 30% were P0 or P1 issues caught before they impacted trading. Every one of those P0/P1 catches justified the entire system.</p><p>The repository has 12 GitHub Actions workflows. Not because I love YAML — because each one prevents a specific class of failure.</p><p>Three of these deserve a deep dive because they’re the ones that ship code fast without shipping bugs.</p><p>SageMaker containers are expensive to rebuild — 15 minutes for the PyTorch training image. But the ML scripts change far more often than the container dependencies. The bootstrap pattern decouples them: containers download scripts from S3 at startup.</p><p>deploy-scripts.yml syncs scripts to S3 and writes a manifest:</p><p>Every SageMaker job’s bootstrap.sh downloads from s3://bucket/scripts/{type}/latest/. The manifest means I can always answer &quot;what version of the processing script did this job use?&quot; without digging through git.</p><p>From push to S3: 30 seconds. From push to a SageMaker job using the new script: the next time the job runs, it picks up the latest. No container rebuild. No redeployment.</p><p>Before the bootstrap pattern, every script change triggered a full container rebuild: install PyTorch, install scikit-learn, copy scripts, push to ECR. 15 minutes per iteration. I was sometimes making 5–6 script changes per day during pipeline development — that’s 90 minutes of CI time just waiting for containers. The bootstrap pattern reduced each iteration to 30 seconds. Over a month of active pipeline work, that’s roughly 30 hours saved.</p><p>This workflow builds 7 container images, but only the ones that changed. It uses dorny/paths-filter to detect which paths were modified, then runs a matrix build that skips unchanged containers:</p><p>That comment is the bootstrap pattern in action. Script changes don’t trigger 15-minute container rebuilds anymore.</p><p>The deployment step auto-detects whether each ECS service uses blue-green (CodeDeploy) or rolling updates:</p><p>No manual workflow selection. No “did someone flip the flag?” The workflow asks ECS what deployment controller each service uses and acts accordingly.</p><p>For blue-green services (backend and frontend), the deployment creates an AppSpec that CodeDeploy uses to stand up “green” replacement tasks. Traffic starts flowing to the green tasks through a test listener on port 8443 (VPC-internal only) for validation. Once healthy, CodeDeploy shifts all production traffic at once, then terminates the “blue” original tasks after a 5-minute grace period for in-flight requests. If the green tasks fail health checks or a CloudWatch 5xx alarm fires, CodeDeploy automatically rolls back — production traffic returns to the blue tasks without manual intervention.</p><p>For the worker service, it’s a straightforward rolling update — no ALB, so blue-green doesn’t apply. The workflow handles both paths from the same code, determined entirely by what ECS reports.</p><p>The ML pipeline orchestrator Lambda is the brain of the entire 9-stage pipeline. A bad deploy there could corrupt pipeline state, advance stages incorrectly, or silently lose training jobs. So it doesn’t get instant promotion.</p><p>Utility Lambdas (training trigger, alert handler) get instant alias promotion. Critical Lambdas (ML pipeline orchestrator, RL pipeline orchestrator) get 10% traffic for 120 seconds, a CloudWatch error check, then either promotion to 100% or automatic rollback. The observation window runs in parallel for all canaries — total CI time is ~2 minutes, not 2 minutes per function.</p><p>One test job runs on every push, regardless of what changed:</p><p>Change detection doesn’t skip it. The test-summary job depends on it with if: always(). Why? Because the $78,947 loss was fundamentally a feature consistency failure - the RL model fell back to heuristics for two weeks because inference couldn&#39;t produce the features that training expected. This test ensures training and inference feature lists never drift apart, even if the change looks unrelated.</p><p>The system runs in two modes — AWS (production) and Local (development) — with the same application code. Mode detection is three environment variables:</p><p>Feature flags, not branches. The code reads if settings.SAGEMAKER_ENABLED and calls SageMaker or loads from disk. No separate codepaths, no local-only forks that drift from production.</p><p>The infrastructure swaps out cleanly:</p><p>The Local pipeline orchestrator stores state in PostgreSQL instead of SSM but uses the same stage progression logic. When I add a pipeline stage, I implement it once — the orchestrator abstraction handles the storage difference.</p><p>The key is that mode detection happens at the infrastructure boundary, not in the business logic. The prescreening service doesn’t know whether it’s calling a SageMaker endpoint or loading a local scikit-learn model from disk — it gets a prediction back either way. The pipeline orchestrator doesn’t know whether it’s writing state to SSM or PostgreSQL — it calls update_state() and the backend handles the rest.</p><p>This means I can reproduce production failures locally. When a SageMaker processing job fails because of a feature computation bug, I run the same computation in Spark locally, fix the bug, verify locally, then deploy the fix via deploy-scripts.yml. The SageMaker container picks up the fixed script at next run - 30 seconds to S3, no container rebuild.</p><p>Why this matters for iteration speed: I can test pipeline changes locally against Spark before burning SageMaker compute. A full local pipeline run takes 20 minutes on my laptop. The same run on SageMaker takes 45 minutes and costs money. Getting the logic right locally first saves both time and dollars. Over the past two months, this has probably saved 40+ SageMaker hours of “oops, wrong column name” iterations.</p><p>The ML pipeline has 9 stages:</p><pre>Backfill → Export OHLCV → Feature Computation → Processing/Scoring → <br>Prescreening HPO → Score Generation → RL Ensemble Training (PPO+SAC+TD3)</pre><p>On AWS, it’s fully event-driven. The Lambda orchestrator can’t run for more than 5 minutes (hard AWS limit), so it delegates compute to SageMaker Processing and Training jobs. When a job completes, a CloudWatch Events rule fires the orchestrator again. The orchestrator checks the job status, writes the new state to SSM ({&quot;stage&quot;:&quot;feature_computation&quot;,&quot;jobs&quot;:{...},&quot;started_at&quot;:&quot;...&quot;}), and launches the next stage&#39;s job. If any stage fails, the pipeline stops - no silent advancement, no &quot;well, let&#39;s try the next stage anyway.&quot;</p><p>This event-driven design means the pipeline can run for hours without any single process running for more than a few seconds. A full monthly pipeline — all 9 stages including RL ensemble training across 3 algorithms — takes 3 to 4 hours wall clock. The orchestrator Lambda invokes maybe 20 times total, each invocation under 30 seconds.</p><p>Prescreening hyperparameter optimization runs 90 Bayesian trials across 6 model variants (buy and sell, across 3 volatility regimes: low, medium, high). It used to have inner cross-validation, but I removed it in February 2026 — inner CV was causing overfitting by letting the optimizer exploit fold-specific patterns. The models trained without inner CV generalized better to unseen data. Sometimes the right optimization is removing optimization.</p><p>This is the system I’m most proud of. The execution layer — the code that decides <em>when</em> and <em>how much</em> to trade — has 33 tunable parameters: entry thresholds, exit thresholds, cooldown periods, position size caps, stop-loss levels, take-profit targets, momentum filters, exposure limits.</p><p>Tuning these by hand is hopeless. Tuning them with live trades is expensive. Monte Carlo parameter tuning does neither.</p><p>The system uses Latin Hypercube Sampling to generate parameter sets (500 weekly, 1000 monthly), then replays each set against historical trades in simulation. No market interaction. No risk. A full weekly run — 500 samples across 28 days of data — completes in 8 to 20 minutes.</p><p>The replay simulator handles timing gates correctly via a deferred action queue. When a parameter set includes market_open_buffer=15 (don&#39;t trade in the first 15 minutes) or min_hold_minutes=30 (hold positions for at least 30 minutes), the simulator doesn&#39;t skip those trades - it defers them to the correct future timestamp and executes at that timestamp&#39;s actual price. This matters because &quot;skip&quot; and &quot;defer&quot; produce very different P&amp;L. A trade skipped at 9:31 AM and a trade deferred to 9:46 AM can have meaningfully different fill prices.</p><p>Five guardrail gates protect against overfitting:</p><ol><li><strong>Composite improvement</strong>: the new set must improve the composite metric by at least 10% over current production values</li><li><strong>Max drawdown</strong>: must not exceed 1.5x the current drawdown</li><li><strong>Minimum trades</strong>: at least 20 trades in the simulation window (prevents parameter sets that “win” by rarely trading)</li><li><strong>Safety bounds</strong>: all 33 parameters must stay within their defined ranges</li><li><strong>CV overfit check</strong>: validation performance must be at least 50% of training performance (k-fold cross-validation on the simulation window)</li></ol><p>When a parameter set clears all 5 gates, it writes to the settings database. The execution layer picks up new parameters via SettingsService with a 60-second cache - no redeployment, no restart. The bootstrap pattern, applied to configuration.</p><p>Weekly tuning runs after Sunday calibration (500 samples, 28-day lookback). Monthly tuning runs after the full RL pipeline completes (1000 samples, 90-day lookback). Both are triggered automatically by the pipeline orchestrator — weekly via EventBridge schedule, monthly via the RL pipeline completion event.</p><p>The parameter registry defines all 33 parameters with their types, bounds, defaults, and descriptions. Adding a new tunable parameter is a single registry entry — the LHS sampler, simulator, and settings bridge all pick it up automatically. This is how I went from 12 parameters to 33 over 6 weeks without touching the tuning infrastructure.</p><p>For comparing strategies head-to-head, the system has an A/B testing framework with ORM models for variant assignment, time-series metric snapshots, and trade attribution. Control vs treatment strategies — full ML stack, RF-only, RL-only — each get separate paper trading accounts with dedicated Alpaca API credentials. The framework tracks per-variant P&amp;L, Sharpe ratio, max drawdown, and win rate over configurable windows. This lets me answer “does the RL ensemble actually add value over prescreening alone?” with data, not intuition.</p><p>The feature system has two canonical lists, and the boundary between them is explicit.</p><p><strong>RL_MODEL_FEATURES</strong> - 40 features used by the RL portfolio model:</p><pre># backend/app/ml/features.py <br>RL_MODEL_FEATURES = [ <br># Technical (16): return, log_return, sma_fast, sma_slow, ... <br># Prescreening scores (2): buy_probability, sell_probability <br># Intraday (3): opening_gap_pct, intraday_momentum_1h, relative_strength_vs_spy <br># Core fundamental (6): market_cap_log, beta, pe_ratio_norm, ... <br># FMP extended (13): analyst_revision_momentum, earnings_surprise_streak, ... <br>] # This is the SINGLE SOURCE OF TRUTH for the RL portfolio allocation model.</pre><p><strong>EXTERNALLY_MERGED_FEATURES</strong> - 25 features that come from external data sources, not OHLCV computation:</p><pre># backend/sagemaker/compute_features_parallel.py <br>EXTERNALLY_MERGED_FEATURES = {<br># &quot;buy_probability&quot;, &quot;sell_probability&quot;, &quot;timeframe_encoded&quot;, <br># Core FMP (6): market_cap_log, beta, pe_ratio_norm, ... <br># Extended FMP (16): analyst_revision_momentum, ... <br>}</pre><p>This set tells the feature computation pipeline “don’t try to compute these from price data — they come from FMP API data merged in the processing stage.” The validation logic uses it as a gate:</p><p>If a feature is neither OHLCV-computed nor listed in EXTERNALLY_MERGED_FEATURES, the script raises a ValueError and the SageMaker job fails fast. No silent NaN columns. No &quot;the model will probably figure it out.&quot;</p><p>The CI gate — the test-features job that runs on every push with no skip condition - verifies these lists stay in sync. It checks that ML_FEATURE_NAMES has exactly 79 features, RL_MODEL_FEATURES has exactly 40, and that every feature declared in training exists in inference. The expected counts are hardcoded constants:</p><pre>EXPECTED_ML_FEATURE_COUNT = 79 <br> 41 base + <br> 15 intraday + <br> 10 sell + <br> 10 buy + <br> 13 FMP <br>EXPECTED_RL_FEATURE_COUNT = 40</pre><p>Change either list without updating the other, and CI blocks the merge. This is the direct response to the $78,947 loss — the RL model silently fell back to heuristics for two weeks because inference couldn’t produce features that training expected. That failure now has a hard gate in CI that no amount of “it looks fine to me” can bypass.</p><p>The concrete iteration cycle: code change, push to branch, tests run in parallel (3 to 5 minutes), merge to main, blue-green deploy (~2 minutes), trading-health verifies (~1 minute). Total: under 10 minutes from idea to verified production.</p><p>The ML experiment cycle is even faster for script-only changes: modify a training or processing script, push, deploy-scripts.yml syncs to S3 in 30 seconds, trigger the pipeline stage, monitor. No container rebuild. No redeployment.</p><p>What one person ships in a typical week: 2–3 full pipeline runs, a weekly MC parameter tuning pass, Sunday model calibration, 5–10 bug fixes or enhancements, and the occasional new feature — all with automated safety nets catching issues before market open. The health check has caught issues at 6:45 AM that would have cost real money by 9:31 AM.</p><p>The development pattern that makes this sustainable: I don’t context-switch. The system surfaces what needs attention (trading-health, daily-report, issue backlog), I fix the highest-priority item, CI/CD deploys it, and the next health check confirms it. If nothing is broken, I work on the feature roadmap. If something is broken, I know within minutes, not hours.</p><p>None of this is magic. It’s 12 workflows, 13 policies, 2 automated health checks, 5 guardrail gates, and a CLAUDE.md file that remembers every expensive mistake. The system doesn&#39;t prevent all failures - it prevents the same failure twice.</p><p>That Sunday calibration failure from the opening of this post? It happened. The health check caught it at 6:45 AM Monday. I pushed a fix at 7:12 AM. Blue-green deployed it by 7:15 AM. Trading-health confirmed the fix at 7:20 AM. Market opened at 9:30 AM. All 6 prescreening endpoints returned fresh predictions. Total time from detection to verified production: 35 minutes. Total stress: minimal — because every step of the response was a system, not a scramble.</p><p>In the next post, I’ll show what all of this produces: a week of paper trading results, position by position, with the numbers that prove whether the system actually works.</p><p><em>This is Post 7 of an 8-part series on building a full-stack AI trading application with LLM coding agents. </em><a href="https://gist.github.com/ttarler/c05b7225cd4fbfb0f283e31fa820497a"><em>Previous: The Documentation System That Prevents Knowledge Loss</em></a><em> | </em><a href="https://gist.github.com/ttarler/c05b7225cd4fbfb0f283e31fa820497a"><em>Next: Proof It Works — A Week of Paper Trading Performance</em></a><em>The system tells agents what to do, the documentation tells them what NOT to do. Next: whether any of it actually makes money.</em></p><p><em>Originally published at </em><a href="https://gist.github.com/ttarler/c05b7225cd4fbfb0f283e31fa820497a"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd934f7dae08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Post 6: Documentation That Deploys]]></title>
            <link>https://medium.com/@ttarler/post-6-documentation-that-deploys-029d4e350143?source=rss-4389f5a6ff54------2</link>
            <guid isPermaLink="false">https://medium.com/p/029d4e350143</guid>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Thomas Tarler]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 18:45:36 GMT</pubDate>
            <atom:updated>2026-03-11T18:45:36.626Z</atom:updated>
            <content:encoded><![CDATA[<p>Between January 9 and January 30, 2026, our AI-assisted trading system had seven significant incidents. The same root patterns — silent fallbacks, unverified deployments, training/inference mismatches — kept recurring despite post-mortems and a growing LESSONS_LEARNED.md. The lessons existed. The enforcement mechanism didn&#39;t.</p><p>This post is about the documentation system that emerged from those failures. Not documentation in the wiki sense — a self-reinforcing system where every incident writes the rules that prevent the next one, and those rules are embedded in the tools that AI coding agents read at the start of every session.</p><p>Post 5 ended with a tease: “I’ll go deeper on the documentation system in the next post, including why we built it, how it prevents the kind of knowledge loss that contributed to our $78K incident, and how it works with AI coding agents.” Here’s the full story.</p><p>AI coding agents lose context between sessions. A lesson learned Tuesday is forgotten Thursday. This isn’t a minor inconvenience — it’s an operational risk.</p><p>Between January 9 and February 6, 2026, I logged seven significant incidents:</p><p>These weren’t seven independent failures. They were variations on three themes: silent fallbacks masking broken systems, deployments assumed to work without verification, and training code leaking into inference containers.</p><p>We had post-mortems. We had a LESSONS_LEARNED.md. Incidents kept happening because there was no mechanism to turn a lesson into a constraint that an AI agent would respect on its next session. The post-mortem for Jan 12&#39;s silent fallback explicitly documented &quot;NEVER use try/except with silent fallback for model inference.&quot; Six days later, the Jan 30 loss was caused by the exact same pattern - the RL endpoint&#39;s silent fallback to heuristics. The lesson existed. The enforcement mechanism didn&#39;t.</p><p>The question became: how do you make documentation that doesn’t just record knowledge, but actively prevents the recurrence of the failures it documents?</p><p>The answer turned out to be four concentric layers, each with a different audience, update frequency, and enforcement mechanism. The innermost layer is the most concentrated and the most frequently consulted. Each outer layer adds depth and context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fkg4AjgT-ZHfcgU4" /></figure><p>CLAUDE.md sits at the repository root. AI coding agents load it automatically at the start of every session. It&#39;s the single most important file in the documentation system because it&#39;s the only one that&#39;s always in context.</p><p>It contains 12 policies. Each one traces directly to a specific failure:</p><p>The mapping from policies to incidents is direct:</p><ul><li><strong>Policy 3</strong> (“Verify deployments”) ← Jan 14: RL model “deployed” but never actually loaded. Agent reported success without checking logs.</li><li><strong>Policy 4</strong> (“Fail fast, never silently”) ← Jan 12 and Jan 30: Silent fallback to heuristics masked complete model failure for weeks.</li><li><strong>Policy 6</strong> (“Separate training/inference code”) ← Feb 6: Used RLlib training script as inference entry point. Ray import caused a segfault. Five hours lost.</li><li><strong>Policy 10</strong> (“Urgent failures = act first”) ← Feb 17: SageMaker jobs burning money while we debated the correct CI/CD process.</li></ul><p>Each policy is a scar. The CLAUDE.md file isn’t a style guide or a wish list — it’s a compressed version of every expensive mistake we’ve made, written in imperative language that an AI agent can follow without ambiguity.</p><p>CLAUDE.md tells agents what to do and what not to do, but it doesn&#39;t explain why, and it doesn&#39;t provide code examples. That&#39;s what the knowledge base is for.</p><p>.ai-knowledge-base.yaml is a 620-line structured YAML file containing 8 patterns (do this), 6 anti-patterns (don&#39;t do this), and 4 decision-tree scenarios. Each entry has a consistent schema:</p><p>The key difference from CLAUDE.md: this file is structured enough for programmatic consumption. An AI agent can look up patterns by id, filter by severity: CRITICAL, or follow a decision tree step by step. The do and dont arrays are unambiguous directives. The checklist provides sequential verification steps. The reference_files field points to the exact source code locations where the pattern applies.</p><p>This is the difference between “don’t use silent fallbacks” (CLAUDE.md) and “here’s exactly what a silent fallback looks like in code, here’s what to do instead, here’s how to verify you didn’t introduce one, and here’s the post-mortem that proved why this matters” (knowledge base).</p><p>The docs/v2/ops/ directory contains the procedures that turn policies into actions. Morning go/no-go checklists. Deployment procedures. Hotfix and rollback playbooks. Pipeline troubleshooting guides.</p><p>Every runbook includes YAML frontmatter:</p><p>The morning go/no-go checklist was a direct response to the Jan 9 EventBridge incident, where all trading rules were disabled and nobody noticed until 23 minutes before market open. Now, every trading day starts with a single endpoint call that checks service health, trading operations, risk controls, data freshness, ML model availability, and watchlist readiness. It returns a boolean: overall_ready: true or overall_ready: false. No ambiguity. No room for an AI agent to assume systems are working without checking.</p><p>The depends_on field creates a navigable graph. The go/no-go checklist depends on the daily operations doc and the monitoring setup doc. An agent troubleshooting a pre-market failure can follow these links to find the relevant context.</p><p>The outermost layer provides full depth: system architecture, risk controls, model design, feature engineering, infrastructure, and more. The master index ( docs/v2/INDEX.md) organizes everything into four perspectives - Architecture, Risk, Operations, and System Guide - with an &quot;I need to...&quot; lookup table:</p><p>Understand the overall system</p><p>arch/01-system-overview.md</p><p>Debug a pipeline failure</p><p>ops/08-troubleshooting-pipeline.md</p><p>Deploy a code change</p><p>ops/03-deployment-checklist.md</p><p>Fix a production issue fast</p><p>ops/04-hotfix-and-rollback.md</p><p>Understand risk controls</p><p>risk/02-trading-risk-controls.md</p><p>Check model risk incidents</p><p>risk/15-risk-incidents-and-lessons.md</p><p>Pre-market morning checklist</p><p>ops/05-trading-morning-go-no-go.md</p><p>Understand feature engineering</p><p>risk/07-feature-engineering.md</p><p>This table is explicitly designed for AI agents. An agent that needs to deploy a code change doesn’t need to know the documentation structure — it reads the lookup table and goes directly to ops/03-deployment-checklist.md. The agent discovery section includes grep commands:</p><p>The cross-references create a graph. From any document, an agent can discover related documents through depends_on, related source code through key_files, and topical connections through tags.</p><p>The four layers only matter if they’re connected to the incidents that justify them. Here’s how a single incident — our worst production loss — propagated through every layer of the documentation system. The point isn’t the incident itself (I covered that in earlier posts). The point is the <em>process</em> — how a failure becomes a permanent system constraint.</p><p>January 30, 2026. A single stock crashes 74%. Multiple safeguards fail simultaneously — the RL model had been silently falling back to heuristics, position limits didn’t account for pending orders, and compliance defaulted to “allow” for unclassified sectors.</p><p>The post-mortem followed a structured template — 12 mandatory sections (Summary, Timeline, Root Cause, Impact, What Went Well, What Went Wrong, Action Items, Lessons Learned, Prevention). No optional sections. If you can’t fill a section, you haven’t investigated deeply enough.</p><p>The template’s most important feature: it requires <em>multiple</em> root causes. This investigation identified five — infrastructure misconfiguration, silent fallback behavior, incomplete validation logic, permissive defaults for missing data, and insufficient monitoring. A single-root-cause analysis would have fixed the infrastructure issue and declared victory, leaving four other holes open for the next incident.</p><p>The “silent fallback” pattern was formalized in .ai-knowledge-base.yaml as a CRITICAL anti-pattern. The &quot;feature verification&quot; pattern was added as a CRITICAL positive pattern with an explicit checklist: code written → tests passing → deployed → verified in production → documented with evidence.</p><p>Three CLAUDE.md rules trace directly to this incident:</p><ul><li><strong>Policy 3</strong> (“Verify deployments”): “Deployed” ≠ “Working”. Always check logs.</li><li><strong>Policy 4</strong> (“Fail fast, never silently”): No try/except fallbacks that mask failures.</li><li><strong>Policy 7</strong> (“Feature consistency”): Training and inference must use identical feature lists.</li></ul><p>The morning go/no-go checklist now includes SageMaker endpoint verification — confirming that every endpoint is InService and responding within latency thresholds. The deployment checklist now includes a mandatory log verification step.</p><p>Four code changes shipped the same day — each one addressing a specific root cause from the post-mortem: remove the silent fallback (fail fast instead), block trades with missing data (reject unknowns instead of allowing), include pending orders in concentration limits, and add portfolio risk validation before every buy.</p><p>Feature consistency validation runs on every PR. features.py is the single source of truth for model feature lists. If the training feature list diverges from the inference feature list, CI fails. No exception. No override.</p><p>The feedback loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wnb0OVi_H32gUWIl" /></figure><p>Every incident feeds every layer. The layers reinforce each other: CLAUDE.md tells agents what to do, the knowledge base explains why and how, the runbooks provide step-by-step procedures, and CI gates enforce the rules in code. An incident that passes through all seven steps of this loop has been converted from a one-time lesson into a permanent system constraint.</p><p>Every incident in the system gets a dollar amount. Not an estimate, not a range — a specific cost entry in MISHAP_COST_LOG.md.</p><p>The file opens with a cost reference table:</p><p>Then each session’s incidents follow a consistent template:</p><p>The dollar amounts serve two purposes. First, accountability — it’s harder to dismiss an incident as minor when you can see it cost $55–90 in wasted compute. Second, prioritization — the entries that cost the most get the most aggressive prevention measures.</p><p>What matters more than any individual dollar amount is the pattern recognition. When you aggregate costs by <em>category</em> rather than by date, the same root patterns emerge that the incident table showed earlier — silent fallbacks, unverified outputs, architecture mismatches. The mishap log makes these patterns impossible to ignore because they have cumulative price tags.</p><p>The $0-cost near-misses are arguably the most valuable entries. The Jan 13 alphabetical bias — where prescreening only ever considered stocks starting with “A” because the broker API returns symbols alphabetically and the code took universe[:500] - cost nothing because it was caught during paper trading review. But it revealed that the prescreening pipeline had never been validated for output diversity. That led to the broader principle: verify outputs, not just execution. The system learned before paying.</p><p>The mishap log creates a culture of measurement. When an agent makes a mistake, it doesn’t just get a post-mortem — it gets a price tag. Over time, the cumulative cost data makes the value of the documentation system concrete. Every dollar in the mishap log is a dollar that the feedback loop is designed to prevent from recurring.</p><p>Every document in the system includes YAML frontmatter. This isn’t cosmetic — it’s the mechanism that makes the documentation discoverable by AI agents.</p><p>The frontmatter fields are designed for programmatic consumption:</p><ul><li><strong>id</strong>: Stable reference for cross-linking (depends_on: [risk-10])</li><li><strong>perspective</strong>: One of four categories (architecture, risk, operations, guide)</li><li><strong>tags</strong>: Topical classification for search</li><li><strong>depends_on</strong>: Explicit dependency graph between documents</li><li><strong>key_files</strong>: Source code files that this document describes</li></ul><p>An agent investigating a production incident can start with the “I need to…” lookup table, find the relevant runbook, follow depends_on links to understand the broader context, and trace key_files to the exact code that needs attention. The frontmatter turns a flat directory of markdown files into a navigable knowledge graph.</p><p>The post-mortem template itself is documentation as code. Its 12 mandatory sections enforce investigative rigor:</p><ol><li>Summary</li><li>Timeline</li><li>Root Cause</li><li>Impact (financial, users, duration)</li><li>What Went Well</li><li>What Went Wrong</li><li>Action Items (with owner, status, due date)</li><li>Lessons Learned</li><li>Prevention</li></ol><p>The “What Went Well” section is often the hardest to fill — it forces you to identify what parts of the system worked correctly during a failure, which prevents over-correction. In our worst incident, the prescreening model and the stop-loss system both functioned as designed. Those details matter because they prevent the knee-jerk reaction of dismantling working components alongside the broken ones.</p><p>The clearest way to see the documentation system’s value is to compare two incidents: one before the system existed, and one after.</p><p>Task: Deploy new RL model to production.</p><p>The agent used the RLlib training script as the inference entry point. Ray imported at module load time. The SageMaker inference container didn’t have Ray installed. Segfault.</p><p>Five hours of debugging followed. The agent tried adding packages, removing custom entrypoints, rebuilding containers — none of it worked because the root cause (training code in the inference path) wasn’t identified until hour four. Zero trades executed that morning. The fix — creating a standalone inference.py that duplicates the model architecture without Ray imports - took 30 minutes once the problem was understood. The other 4.5 hours were wasted.</p><p>Same task: Deploy updated RL model to production.</p><p>The agent reads CLAUDE.md at session start. Policy 6 is explicit: “Separate training/inference code — Ray imports in inference containers = segfault. Duplicate model architecture instead.” The agent opens the knowledge base, finds the deployment_process pattern, and follows the deployment checklist from ops/03-deployment-checklist.md.</p><p>The checklist includes: verify inference module has no training-only imports, build container locally, test inference with sample payload, deploy to SageMaker, verify endpoint is InService, invoke with test data, check CloudWatch logs for errors.</p><p>The agent creates the standalone inference module, tests it locally, deploys, verifies the endpoint responds, checks the logs for any errors — and is done in 30 minutes. No segfault. No five-hour debugging session. No missed trading window.</p><p>The difference isn’t that the agent is smarter. It’s that the system contains the answer to a problem that was already solved once. The Feb 6 post-mortem identified the root cause. The CLAUDE.md policy encoded the constraint. The knowledge base provided the code pattern. The deployment checklist provided the verification steps. Each layer added a guardrail, and the guardrails compound.</p><p>This is what I mean by documentation that deploys. It doesn’t sit in a wiki waiting to be read. It’s loaded into the agent’s context at session start, structured for programmatic lookup, and connected to the verification steps that prove the deployment actually works.</p><p>If you’re working with AI agents and want to build a similar system, here’s where to start:</p><ol><li><strong>Start with a mishap log.</strong> Track every mistake with a dollar amount. Even $0 near-misses deserve an entry. The act of quantifying forces you to take incidents seriously and creates the data you need to prioritize prevention.</li><li><strong>Write post-mortems with multiple root causes.</strong> Single-root-cause analysis is almost always incomplete. Force yourself to find at least three contributing factors. Use a template with mandatory sections so you can’t skip the hard parts.</li><li><strong>Encode policies where agents read them.</strong> If you’re using AI coding agents, put your most critical rules in the file that loads automatically every session. For Claude, that’s CLAUDE.md. For other tools, find the equivalent. Twelve imperative rules beat a hundred pages of guidelines.</li><li><strong>Structure knowledge for machines, not just humans.</strong> Prose documentation is for context. Structured YAML (or JSON, or whatever your agents parse) is for enforcement. Include severity levels, code examples, verification steps, and reference files.</li><li><strong>Create the feedback loop.</strong> The system only works if every incident propagates through all layers: incident → post-mortem → pattern/anti-pattern → policy → runbook → code change → CI gate. Skip any step and the loop has a gap.</li><li><strong>Treat documentation updates as part of the fix.</strong> When you close an incident, the code change is half the work. The policy update, the runbook update, and the knowledge base entry are the other half. If you don’t update the documentation, you’ll fix the same problem twice.</li></ol><p>The investment is real — building and maintaining four documentation layers takes time. But the alternative is paying for the same lesson more than once. The documentation system exists to make sure every failure only happens once.</p><p><em>This is Post 6 of an 8-part series on building a full-stack AI trading application with LLM coding agents. </em><a href="https://gist.github.com/ttarler/0f4784045b11d6bfbc37a8de1b9b4f3e"><em>Previous: The Ensemble That Actually Trades — How PPO, SAC, and TD3 Became One Decisioning System</em></a><em> | </em><a href="https://gist.github.com/ttarler/0f4784045b11d6bfbc37a8de1b9b4f3e"><em>Next: One Developer, 12 Workflows, and a Production ML System</em></a><em>The documentation system tells agents what NOT to do. Next week: the full development system that lets one person ship production ML at startup speed.</em></p><p><em>Originally published at </em><a href="https://gist.github.com/ttarler/0f4784045b11d6bfbc37a8de1b9b4f3e"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=029d4e350143" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ensemble That Actually Trades — How PPO, SAC, and TD3 Became One Decisioning System]]></title>
            <link>https://medium.com/@ttarler/the-ensemble-that-actually-trades-how-ppo-sac-and-td3-became-one-decisioning-system-abfd263a136f?source=rss-4389f5a6ff54------2</link>
            <guid isPermaLink="false">https://medium.com/p/abfd263a136f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Thomas Tarler]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 22:01:36 GMT</pubDate>
            <atom:updated>2026-03-03T22:01:36.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2mbGy2eO-KsVg1-c" /></figure><p>I spent weeks training a single PPO agent to make portfolio decisions. It worked well in calm markets. Then VIX spiked from 14 to 22 and the model froze — its learned policy didn’t generalize to a volatility regime it hadn’t trained in.</p><p>This isn’t a novel observation. Any quantitative researcher who’s deployed a single model to trade across regimes has hit this wall. The issue isn’t the algorithm. It’s that markets have structural breaks — volatility regimes, sector rotations, macro shocks — and no single model captures all of them.</p><p>So I built an ensemble. Not the textbook kind where you average three identical models with different random seeds. I mean a multi-layered system where fundamentals, technicals, ML prescreening, and reinforcement learning each contribute an independent signal, and a regime-aware decision engine merges them into a single conviction score.</p><p>This post is about how that system works, the experiments that shaped it, and three days of paper trading that proved the architecture generates real alpha.</p><p>The entire pipeline is a funnel. 8,000+ symbols come in. A handful of buy/sell/hold decisions come out. Every layer in between adds a different kind of intelligence.</p><pre>Raw Market Data (OHLCV, 8,000+ symbols) │ ▼ Feature Engineering (40+ indicators) │ ├── Momentum: RSI, MACD, rate of change ├── Volatility: ATR, Bollinger Bands, vol-of-vol ├── Trend: SMA crossovers, ADX, directional movement ├── Volume: relative volume, OBV slope, VWAP distance └── Market context: VIX level, VIX change, relative strength vs SPY │ ▼ VIX Regime Detection → determines WHICH models run, HOW signals are weighted │ ▼ ┌─────────────────────────────────────────────────────────┐ │ PRESCREENING (Random Forest + XGBoost) │ │ 6 models: buy/sell × low/moderate/high volatility │ │ Input: 40+ technical + 6 fundamental features │ │ Output: buy_probability, sell_probability per symbol │ │ 8,000 symbols → 50 candidates │ └─────────────────────────────────────────────────────────┘ │ prescreening scores become RL input features ▼ ┌─────────────────────────────────────────────────────────┐ │ RL INNER ENSEMBLE (PPO + SAC + TD3) │ │ 3 algorithms, each trained via Bayesian HPO │ │ Input: 44 features per stock (technicals + scores │ │ + portfolio state + fundamentals) │ │ Output: continuous action [-1, 1] per stock │ │ Assembly: composite-weighted (SAC 40%, TD3 32%, │ │ PPO 28%) │ └─────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────┐ │ OUTER ENSEMBLE DECISION ENGINE │ │ 4 signal sources: Prescreening, RL, Technical, │ │ Fundamental │ │ Regime-dependent weights │ │ Agreement scaling + coverage penalty │ │ Output: BUY / HOLD / SELL + conviction score │ └─────────────────────────────────────────────────────────┘ │ ▼ Portfolio Optimizer (Max-Sharpe, Ledoit-Wolf covariance) │ ▼ Risk Controls → Execution</pre><p>The key design principle: <strong>each layer uses the same underlying data differently.</strong> Prescreening uses raw features for cross-sectional classification (“is this stock worth looking at?”). RL uses them as part of a sequential decision (“given my current portfolio, should I buy more?”). The outer ensemble uses them as independent corroborating signals (“do multiple perspectives agree?”).</p><p>This isn’t redundancy. It’s triangulation.</p><p>VIX regime detection isn’t a feature. It’s the control plane. It determines which prescreening models run, how the RL signal is weighted, how large positions can be, and whether trading happens at all.</p><p>The prescreening stage trains six separate models — one for each combination of action (buy, sell) and volatility regime (low, moderate, high). At training time, each HPO job filters its data to the relevant regime’s VIX range, so the buy-low-vol model only sees calm-market data and the sell-high-vol model only sees turbulent data.</p><p>RL models train across all regimes but receive VIX as a context feature. The reward function shapes behavior differently depending on volatility — drawdown penalties scale with the regime, so the model learns to be more conservative when vol is elevated.</p><p>At inference time, the system checks VIX and routes accordingly:</p><p>The regime then cascades through the entire decision stack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1eHzOWXuyoJyC5BQ" /></figure><p>Position sizing isn’t just a discrete step function. There’s a continuous scaling layer underneath:</p><p>This smooth decay avoids cliff effects. VIX going from 14.9 to 15.1 doesn’t trigger an abrupt regime change at the position level — the continuous function handles the transition.</p><p>For weeks, I had VIX ≥ 25 classified as EXTREME_VOLATILITY, which halts all trading. The problem: VIX hovering around 24-25 during earnings season isn&#39;t a crisis. It&#39;s normal elevated volatility. The portfolio was frozen with zero buys, sells, or rebalancing for extended periods - not because the market was crashing, but because my thresholds were miscalibrated.</p><p>The solution was straightforward: VIX 20–30 is HIGH_VOLATILITY (trade at 50% sizing, defensive posture), and only VIX ≥ 30 is EXTREME (halt). This single threshold change - moving the extreme cutoff from 25 to 30 - allowed the portfolio to rotate during normal elevated-vol periods instead of sitting frozen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TfKe8r83vx5pVvq_" /></figure><p>The same fundamental and technical data feeds into multiple pipeline stages, but each stage uses it differently.</p><p>Six features pulled from Financial Modeling Prep’s API: market_cap_log, beta, pe_ratio_norm, debt_to_equity_norm, roe_norm, revenue_growth. Cached in S3 with a 30-day TTL. A dedicated pipeline stage grabs sector mappings once and writes a shared sector_map.json so all processing partitions reuse it instead of each one independently hitting the API.</p><p>Where fundamentals appear:</p><ul><li><strong>Prescreening features</strong>: Raw values are part of the 40+ feature vector. The RF/XGBoost models learn that a small-cap with high debt and negative ROE is a riskier buy than a profitable mega-cap — something pure technicals can’t distinguish.</li><li><strong>RL observation space</strong>: Part of the 44-feature input per stock. The RL model sees fundamentals alongside technicals and prescreening scores when deciding portfolio allocation.</li><li><strong>Outer ensemble signal</strong>: A standalone 4th signal source that combines PE ratio, ROE, revenue growth, and debt-to-equity into a normalized [-1, 1] composite. This gives the ensemble a fundamentals-based vote independent of the ML models.</li></ul><p>Six indicators computed as a standalone composite for the outer ensemble: RSI (reversal detection), MACD (trend momentum), Bollinger %B (mean reversion), SMA crossover (trend direction), price momentum, and volume confirmation.</p><p>These same indicators also flow into prescreening features and RL observations, but in the outer ensemble they operate as an independent signal source. This proved critical on Feb 27: technical signals of +0.46 to +0.50 overrode prescreening’s sell recommendations (-0.79 to -0.85) on stocks like FIGS (+24%), INDO (+23%), and BATL (+33%). The prescreening model wanted to sell all holdings; the technical signal recognized they were momentum stocks still trending. The ensemble held them. That’s triangulation working as designed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QptyDnD82Ha7OzRm" /></figure><p>Three reinforcement learning algorithms, each trained independently via Bayesian HPO on SageMaker, assembled into a weighted ensemble for inference.</p><p><strong>PPO (Proximal Policy Optimization)</strong>: On-policy, stable, clipped updates. Uses curriculum learning — the buy/sell threshold ramps from 0.05 to 0.15 over 220 training iterations, letting the model first learn “what is a good stock” before requiring decisive actions. Reliable but sample-hungry.</p><p><strong>SAC (Soft Actor-Critic)</strong>: Off-policy, entropy-regularized, sample-efficient. Explores more aggressively because the entropy bonus prevents premature convergence. Got the highest backtest composite score (1.302 vs PPO’s 0.914 and TD3’s 1.042) in the most recent HPO run. No curriculum learning — off-policy replay buffers mix curriculum stages, which defeats the purpose.</p><p><strong>TD3 (Twin Delayed DDPG)</strong>: Deterministic policy, twin critics to reduce Q-value overestimation. Produces precise, non-stochastic action values. Good at avoiding the “optimistic bias” that plagues single-critic methods in noisy financial environments.</p><p>All three share the same network topology — a StockEncoder that processes each stock&#39;s 44 features independently, followed by a StockParallelActor that combines per-stock encodings with a global context vector (mean-pooled across all stocks). This makes the network permutation-equivariant: the decision for AAPL doesn&#39;t depend on AAPL being in slot 3 vs slot 17.</p><p>Input: 1,100 dimensions (25 stocks × 44 features). Output: continuous action in [-1, 1] per stock, squashed through tanh.</p><p>assemble_ensemble.py takes the best checkpoint from each algorithm&#39;s HPO run and combines them:</p><p>Weights are proportional to backtest composite scores: SAC 40%, TD3 32%, PPO 28%. Composite score = excess return over SPY × capped Sortino ratio — this prevents cash-hoarding models from gaming the metric (a lesson from an earlier post in this series).</p><p>The ensemble outputs a continuous value per stock. Three zones:</p><p>For stocks already in the portfolio, the hold zone isn’t wasted. A mildly positive action (say, +0.08) on an owned stock emits a HOLD-AS-BUY signal - the model isn&#39;t enthusiastic enough to cross the buy threshold, but it&#39;s not negative either. This signal gets forwarded to the outer ensemble with reduced strength, preventing signal loss for held positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RT_Z7P6x6-Dz5O6O" /></figure><p>This is where four independent signal sources converge into a single decision. The EnsembleDecisionEngine takes prescreening scores, RL actions, technical indicators, and fundamental metrics - normalizes each to [-1, 1], applies regime-dependent weights, and produces a conviction score.</p><p>The intuition: in calm markets, the RL model has the highest signal-to-noise ratio (it was trained on relatively stable data). In volatile markets, technicals and prescreening carry more weight because RL struggles with distribution shift.</p><p>These defaults are also HPO-tunable. The moderate-volatility weights serve as the base; other regimes are auto-generated by scaling RL up (in low vol) or down (in high vol), with technicals moving in the opposite direction. HPO tunes the base, and the regime variants follow.</p><p>The most important post-weighting step. After computing a raw weighted conviction, the engine asks: “Do the signals actually agree?”</p><p>Agreement then scales the conviction: conviction *= (floor + (1 - floor) * agreement_ratio). With a floor of 0.50, unanimous agreement passes full conviction through, while a 50-50 split reduces it by 25%.</p><p>This prevents overconfident decisions when signals conflict. A stock might have a strong prescreening buy score (+0.80) but a negative RL signal (-0.10) and flat technicals. The weighted average might still be positive, but the low agreement ratio dampens it. The position ends up smaller, which is the right outcome when signals disagree.</p><p>From the March 2 trading session (16:23 UTC cycle):</p><p><em>FIGS is from the Feb 27 session.</em></p><p>DPRO had all four signals positive, agreement of 1.0, conviction of 0.356. Strong unanimous buy. The system bought it.</p><p>FIGS is the more interesting case. Prescreening recommended selling hard (-0.789), but the technical signal was strongly positive (+0.502) — it was a momentum stock that had already rallied 24% on the day. The disagreement dropped agreement to 0.50, and conviction landed at -0.122 — just inside the hold zone. The system held instead of selling. FIGS went on to gain another 4.8% the following session.</p><p>That’s the ensemble working as designed. No single signal source would have gotten FIGS right. Prescreening alone would have sold. Technicals alone would have bought more. The ensemble found the middle ground: hold what you have, don’t add, don’t sell.</p><p>Getting three RL algorithms to produce useful trading signals isn’t a “train once, deploy, done” process. It’s iterative experimentation — tuning hyperparameters, discovering algorithm-specific training dynamics, validating that the assembled ensemble behaves differently from its individual components, and calibrating the parameters between model output and trade execution. Over three weeks, I ran 90+ HPO trials, 20+ sandbox experiments, and migrated the entire training framework. Here’s what that looked like.</p><p>Each algorithm gets 30 Bayesian HPO trials on SageMaker, each running up to 4 hours on a T4 GPU instance. That’s 90 trials total for the three-algorithm ensemble, plus additional runs whenever I changed the search space or reward function.</p><p>The objective metric — backtest_composite = excess_return × min(sortino, 3.0) - was itself the result of experimentation. Early iterations used raw portfolio return, which rewarded models that made a few lucky bets with catastrophic drawdown risk. Sortino ratio alone rewarded models that hoarded cash and never traded. The composite metric requires <em>both</em> alpha generation (excess return over SPY) and risk discipline (downside-adjusted returns), with Sortino capped at 3.0 to prevent gaming.</p><p>The single most impactful finding was that curriculum learning is algorithm-specific. I spent days assuming a universal curriculum would work for all three algorithms. It doesn’t.</p><p><strong>PPO</strong> benefits enormously from a 9-stage curriculum. The buy/sell threshold ramps from 0.05 to 0.15 over ~220 training iterations, letting the model first learn “what constitutes a good stock” before requiring decisive actions. Simultaneously, the episode window expands (200 → 400 → 800 → full history), observation noise decays (0.03 → 0.0 standard deviation), and the learning rate anneals (0.001 → 0.0003 → 0.0001). This staged approach produced stable convergence where a flat curriculum did not.</p><p><strong>SAC</strong> is the opposite. Every sandbox run with curriculum enabled showed <em>declining</em> reward trends. The reason: SAC’s entropy auto-tuning adjusts the exploration-exploitation tradeoff continuously, and staged reward changes interfere with that mechanism. When I disabled curriculum entirely and let SAC’s entropy coefficient self-regulate, it produced its first positive reward trend — and ultimately achieved the highest composite score in the ensemble (1.302).</p><p><strong>TD3</strong> tolerates curriculum but needs wider stage spacing than PPO. Where PPO transitions every 25–50 iterations (25/50/75/100/130/160/190/220), TD3 needs 60/120/180/240/300/370/440/520. The deterministic policy updates are more sensitive to abrupt reward signal changes.</p><p>The initial reward function had an asymmetric treatment of gains and losses — risk penalties applied more aggressively to drawdowns than gains were rewarded. The model converged to a trivial solution: sell everything and hold cash. Zero drawdown, zero alpha, but no penalties either.</p><p>The solution required several adjustments working together: symmetric risk treatment (gains and losses weighted proportionally), a 50x boost to momentum alignment weight (rewarding the model for trading in the direction of the trend), and a 10x activity bonus (penalizing the model for doing nothing when opportunities exist). I also reduced the cash penalty to allow exploration in early curriculum stages — the model needs permission to hold cash while it’s still learning what a good trade looks like.</p><p>The final reward mode is a 3-component “sharpe” function: Differential Sharpe Ratio (captures risk-adjusted return per step), transaction costs (0.1% per trade, prevents churn), and a concentration penalty (discourages loading into a single position). The 11-component “full” reward was too noisy for Bayesian HPO to optimize effectively.</p><p>Before committing to a full HPO run (90 trials × 4 hours = significant compute cost), I built a two-tier sandbox for rapid configuration validation. A local sandbox runs a single trial in ~2–5 minutes and produces a GO/CAUTION/NO-GO verdict based on convergence metrics. Only configurations that pass the sandbox proceed to full SageMaker HPO.</p><p>This saved substantial compute. Over 20+ sandbox experiments, I validated the regularization settings that the production models now use:</p><p>Even with well-tuned training dynamics, the HPO search ranges themselves needed calibration based on the characteristics of the prescreened stock universe.</p><p><strong>Stop-loss thresholds</strong>: The Bayesian optimizer found an “optimal” stop-loss of 2.13%. Mathematically sound — it minimizes expected drawdown in the historical data. Practically useless — the small-cap momentum stocks that the prescreening model selects routinely swing 10–15% intraday. A 2.13% stop-loss triggers on virtually every position within hours. Raising the floor to 5% eliminated spurious stop-outs while maintaining meaningful downside protection.</p><p><strong>Position sizing</strong>: The search range for max_position_pct spans [0.03, 0.10]. At 3%, the model can&#39;t express strong convictions. At 10%, a single bad position can significantly impact the portfolio. The HPO consistently converged to ~5%, which produced realistic 100-200% annualized returns on the holdout period.</p><p><strong>Entropy coefficient (SAC)</strong>: Rather than tuning entropy directly, SAC uses target_entropy_scale in [0.3, 0.7], which sets the target entropy relative to the action dimension. The default of 1.0 (target = -25 for 25 stocks) was too exploratory - action magnitudes stayed too small to cross the ±0.15 buy/sell threshold. Scaling to 0.5 (target = -12.5) produced decisive actions while maintaining sufficient exploration.</p><p>After the full HPO sweep, the three best models and their composite scores:</p><p>SAC’s dominance came from two factors: sample efficiency (off-policy replay buffer reuses experience) and entropy regularization (prevents premature convergence to suboptimal policies). PPO’s lower score reflects its on-policy nature — it requires more data to reach the same level of policy quality, and 30 HPO trials with 220 iterations each may not be enough to fully converge.</p><p>Training models that produce good backtest composites is necessary but not sufficient. The assembled ensemble needs to produce non-degenerate signals when running end-to-end against live market data.</p><p>Validating the full inference pipeline revealed that the RL signal required alignment between the inference endpoint’s output format and the decision engine’s expected input. The composite weights from HPO metadata also needed explicit passthrough to the assembly step — without it, the system defaulted to equal weights (33.3% each) instead of the performance-weighted allocation. I ran both configurations against the Feb 27 session: composite-weighted conviction scores were 5–8% higher on the stocks that ultimately performed best (momentum names like FIGS, BATL, INDO), confirming the weighting scheme adds signal.</p><p>Adding fundamentals as a 4th signal source required standardizing the data format from Financial Modeling Prep’s API. The March 2 session was the first with all four signals active, and the difference was material: DPRO’s conviction of 0.356 with agreement ratio 1.0 (all four sources positive) was the highest-confidence signal the system had generated.</p><p>The ensemble’s signal quality is only as valuable as what the execution layer does with it. Tuning execution parameters — rebalance frequency, minimum trade size, position trim cooldown — matters as much as any model hyperparameter.</p><p>On Feb 26, the execution layer’s rebalance parameters were too aggressive, creating unnecessary position churn that destroyed $1,113 in value that the ensemble had correctly identified. Tightening position management parameters — adding a cooldown between rebalances, setting a minimum trade size of $25, and reducing the rebalance frequency — produced dramatic improvement: roundtrip losses went from -$1,113 (Feb 26) to -$49 (Feb 27) to +$1,369 (March 2). The ensemble’s signals didn’t change between those sessions. The execution configuration did.</p><p>Each experiment followed the same loop: <strong>hypothesize → configure → run against live data → measure at every layer → iterate.</strong> Most of the alpha improvement across these three weeks didn’t come from retraining models. It came from discovering algorithm-specific training dynamics (curriculum helps PPO, hurts SAC), calibrating HPO search ranges to match the actual trading universe, and tuning the parameters between model output and trade execution.</p><p>This is the gap that most ML tutorials skip. The model is maybe 40% of the system. The other 60% is everything surrounding it — reward design, curriculum scheduling, search range calibration, ensemble assembly, signal integration, execution parameters. Getting that right requires running the full pipeline end-to-end and measuring at every layer.</p><p>The real test of an ensemble system isn’t the architecture diagram. It’s the P&amp;L.</p><p>I have three days of paper trading data where the ensemble was live with progressive configuration refinements: Feb 26, Feb 27, and March 2. Each day tells a different part of the story.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GnnAFQDF3RSwmnE0" /></figure><p>The first day of paper trading with the ensemble live. On a day where the S&amp;P 500 fell 0.56%, the portfolio gained 0.58% — an alpha of 1.14%. The prescreening layer identified small-cap momentum stocks that held up well during the broader selloff.</p><p>The execution layer’s rebalance parameters were too aggressive — positions were being trimmed too frequently with no cooldown between rebalances, creating unnecessary churn. Roundtrip losses were -$1,113. Without the excessive rebalancing, the day’s P&amp;L would have been closer to +$1,700. This identified execution parameter tuning as the next experiment to run.</p><p>The RL ensemble identified strong small-cap positions on Feb 26 that gapped up dramatically overnight: FIGS +24%, BDMD +29%, BATL +33%, CDIO +31%. The headline number — nearly +10% in a single day — was largely driven by these overnight moves, with intraday trading roughly flat.</p><p>Two things mattered beyond the raw return:</p><ol><li><strong>Execution parameters tightened</strong>: Position management parameters were adjusted between sessions — minimum trade size, rebalance cooldown, and trim frequency. Roundtrip losses dropped from -$1,113 to -$49, a 96% reduction.</li><li><strong>The ensemble demonstrated its value</strong>: Technical signals of +0.46 to +0.50 overrode prescreening’s sell recommendations (-0.79 to -0.85) on the momentum stocks. Prescreening wanted to sell all holdings; the technical signal recognized they were still trending. The ensemble held, and the portfolio captured the full overnight gap.</li></ol><p>This was the day that validated the full architecture. The portfolio started -$803 below the prior close (overnight gap <em>down</em>). The ensemble recovered that deficit and added +$2,541 during market hours — the first day of genuine intraday alpha generation.</p><p><strong>Roundtrip trades turned positive</strong>: +$1,369 in realized gains. Average winner jumped from $7.68 to $112.87. The 4-signal ensemble — now with fundamentals contributing as a standalone signal source — produced higher-conviction decisions. DPRO had conviction 0.356 with all four signals positive (unanimous buy). The system was generating alpha from its own decisions, not just riding overnight gaps.</p><p>The progression tells the story. Each day was better than the last — not because the models were retrained, but because each experiment refined the inference configuration and made the ensemble architecture more complete. By March 2, all four signal sources were contributing, execution wasn’t destroying value, and the system was making decisions that generated real P&amp;L.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gnwMuDREeHL2Pcdf" /></figure><p>While building the ensemble system, I also built a comprehensive documentation system for the entire trading platform — 4 perspectives (Architecture, Risk, Operations, System Guide), YAML frontmatter for programmatic discovery, and an “I need to…” lookup table that makes it trivial to find the right document for any task.</p><p>On the same day we recalibrated the VIX regime thresholds and the portfolio optimizer, we updated 9 documentation files to reflect the new behavior. Documentation isn’t an afterthought in this system — it’s part of every model update.</p><p>I’ll go deeper on the documentation system in the next post, including why we built it, how it prevents the kind of knowledge loss that contributed to our $78K incident, and how it works with AI coding agents.</p><p><strong>Start with an ensemble from day one.</strong> I wasted weeks trying to make a single PPO agent work across all market conditions before accepting that one algorithm isn’t enough. The ensemble architecture should have been the first design, not the last resort.</p><p><strong>Run end-to-end inference validation before live trading.</strong> Verify that every signal source produces non-zero, non-degenerate outputs across a representative sample of symbols. A format mismatch between the RL output and the decision engine silenced 35.6% of the ensemble’s decision weight for a full trading day. Unit tests on individual components passed fine — the gap was only visible when running the complete inference pipeline end-to-end.</p><p><strong>VIX thresholds need stress testing, not just backtesting.</strong> I backtested the prescreening and RL models extensively but never stress-tested the regime thresholds themselves. VIX 25 as “extreme” seemed reasonable on paper. In practice, it froze the portfolio during normal earnings-season volatility.</p><p><strong>Decompose P&amp;L by signal source.</strong> Total portfolio return hides where alpha is generated and where it’s destroyed. On Feb 26, the ensemble’s stock selection generated +$1,700 of value that the execution layer’s aggressive rebalancing eroded to +$586. Without signal-level attribution, I would have questioned the models instead of the execution parameters.</p><p><strong>The inference system is the product.</strong> Training gets all the attention, but inference — pulling in VIX, routing to the right prescreening model, computing RL features, normalizing signals, applying regime weights, checking agreement, sizing positions — is where the value is actually created. A perfectly trained model with a broken inference pipeline produces nothing.</p><p><em>This is Post 5 of an 8-part series on building a full-stack AI trading application with LLM coding agents. </em><a href="https://gist.github.com/ttarler/9d1541df109a4019a6b0e236d56c3949"><em>Previous: Why 94% Test Coverage Didn’t Stop Our Trading System From Failing</em></a><em> | </em><a href="https://gist.github.com/ttarler/9d1541df109a4019a6b0e236d56c3949"><em>Next: The Documentation System That Prevents Knowledge Loss</em></a></p><p><em>Originally published at </em><a href="https://gist.github.com/ttarler/9d1541df109a4019a6b0e236d56c3949"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abfd263a136f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Medium Post 4: Training an RL Portfolio Agent: 47 Commits of “Why Won’t You Learn to Sell?”]]></title>
            <link>https://medium.com/@ttarler/medium-post-4-training-an-rl-portfolio-agent-47-commits-of-why-wont-you-learn-to-sell-121954646f36?source=rss-4389f5a6ff54------2</link>
            <guid isPermaLink="false">https://medium.com/p/121954646f36</guid>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Thomas Tarler]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 15:50:26 GMT</pubDate>
            <atom:updated>2026-02-23T15:50:26.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xk1TLS3p_lt15J59" /></figure><p>Every RL tutorial on the internet ends the same way: train PPO on CartPole, watch the reward curve go up, celebrate. Maybe they graduate to Atari and show you a DQN playing Breakout.</p><p>None of them prepare you for what happens when your action space has 25 continuous dimensions, your reward signal is delayed by days, and your agent discovers that the optimal policy is to buy everything and never sell.</p><p>I spent about two months getting a reinforcement learning agent to make sensible portfolio decisions. Not “beat the market” decisions-just “don’t hold 98% cash” and “occasionally sell something” decisions. This post is the real story of that process, told through the git log.</p><p>The first RL environment was embarrassingly naive. The model output a weight per stock, softmax normalized to sum to 1, and the environment allocated capital proportionally. Classic portfolio optimization setup.</p><pre>Model output: [0.4, 0.3, 0.2, 0.1, 0.0] Portfolio: 40% AAPL, 30% GOOGL, 20% MSFT, 10% TSLA, 0% NVDA</pre><p>This caused what I started calling “allocation whipsaw.” If the model shifts its preferred weights even slightly between steps, positions get rebalanced. Stock you bought yesterday at 5% allocation? Today the model says 3%. Sells some at a loss. Tomorrow it says 6%. Buys it back. Every rebalance triggers transaction costs. The model was churning its own portfolio to death.</p><p>The deeper problem: there was no concept of “hold.” Every timestep was a full reallocation. The model couldn’t say “I like my current positions, leave them alone.” It had to re-justify every position every day.</p><p>The fix was conceptually simple but mechanically involved. Instead of outputting allocation weights, the model outputs a continuous value in [-1, 1] per stock, and we interpret ranges as discrete actions:</p><p>Now positions persist until the model explicitly says “sell.” No more daily rebalancing. The HOLD zone in the middle gives the model a safe default-when uncertain, do nothing.</p><p>V2 also added explicit position tracking. Each stock slot maintains shares held, entry price, and entry time. The model sees these as additional observation features, so it knows what it’s holding and at what cost basis. Unrealized P&amp;L becomes a signal-the model can learn that a position down 8% might need cutting.</p><p>This was the first version that felt like it could work. It was also the first version where convergence became a nightmare.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eATjfTeP64AsL-vk" /></figure><p>The obvious first architecture: flatten all stock features into one big vector, feed it through a [256, 256] MLP, output 25 actions. With 40 features per stock plus 4 position-state features, that&#39;s a 1,100-dimensional input vector. LayerNorm on the input to prevent activation explosions.</p><pre>Input: (batch, 1100) -&gt; LayerNorm -&gt; MLP(256, 256) -&gt; (loc, scale) per action</pre><p>It trained. Sort of. The problem was subtle: the network had no structural reason to treat stock #3 and stock #17 the same way. Nothing in the architecture enforced that “AAPL in slot 3” and “AAPL in slot 17” should produce similar actions. The model was memorizing slot positions instead of learning stock properties.</p><p>With 25 stocks this was manageable-25 slots, enough data, it learned okay. But when we tried scaling to 50+ candidates? The flat MLP hit a wall. Too many parameters, too little structure.</p><p>The insight was permutation equivariance: the model’s action for stock k should depend on stock k&#39;s features and the portfolio context, not on which slot k happens to occupy.</p><pre>Per-stock features: (batch, K, F+4) | v LayerNorm (per stock) | v Shared StockEncoder: Linear(F+4, 64) -&gt; ReLU -&gt; Linear(64, 64) -&gt; ReLU | (same weights for all K stocks) v Per-stock embeddings: (batch, K, 64) | +---&gt; Masked mean-pool -&gt; global context (batch, 1, 64) | | | v | Project to context_dim | | v v Concat [embed_k, context] for each stock | v Action head: Linear(128, 64) -&gt; ReLU -&gt; Linear(64, 2) -&gt; (loc, log_scale)</pre><p>The StockEncoder uses identical weights for every stock. Same features, same transformation. The masked mean-pool creates a global portfolio summary that every stock can reference for context (&quot;what does the overall portfolio look like right now?&quot;). Then each stock&#39;s action is computed from its own embedding plus the shared context.</p><p>This cut the parameter count significantly and-more importantly-made training converge faster. The model no longer had to independently learn “RSI means the same thing in slot 3 and slot 17.”</p><p>One initialization detail that turned out to matter a lot: the final action head layer gets near-zero weights, with the loc bias at 0.0 and log_scale bias at -1.0. This means the initial policy outputs near-zero actions for everything-HOLD by default. The model has to learn <em>away</em> from holding to start buying or selling. This prevented the early-training chaos of random actions causing huge losses that poisoned the reward signal.</p><p>Here’s where it gets real. Getting this model to converge-to actually learn a useful buy/sell/hold policy-was the hardest part of the entire project. Let me walk through the major failure modes in roughly the order I encountered them.</p><p>The first training runs with V2 produced a model that bought everything it could and never sold. Buy ratio: 95%+. Sell ratio: 0%. The model would ramp up to 100% invested on day 2 and sit there.</p><p>Why? The raw reward was portfolio return minus benchmark return. If the market goes up (which it usually does in our training data), being 100% invested beats holding cash. The model found the global optimum for this reward function: buy everything immediately.</p><p>The fix was an investment band penalty. The model gets penalized for being less than 30% invested (too much cash) OR more than 70% invested (too concentrated). Quadratic penalty in both directions:</p><pre>under_invested: 0.3 * (0.3 - invested_frac)^2 if invested &lt; 30% over_invested: 0.3 * (invested_frac - 0.7)^2 if invested &gt; 70%</pre><p>This created a “Goldilocks zone” where the model is incentivized to be 30–70% invested, not all-in or all-cash.</p><p>After adding the band penalty, I also added asymmetric risk aversion-losses get penalized 1.5x versus gains. Seemed reasonable. What I didn’t anticipate: the model discovered that the safest way to avoid the 1.5x loss penalty is to not hold anything at all.</p><p>This was a subtler version of the cash-hoarding problem. The model would buy a few positions to satisfy the “be at least 30% invested” penalty, then sell them at the first sign of any drawdown. Win rate was terrible because it was cutting winners short and eating transaction costs.</p><p>The fix was risk_aversion_gain_frac -applying a fraction of the asymmetric penalty to gains too. With this set to 0, gains get full credit. The model learns that holding winners is actually rewarding, not just &quot;not losing.&quot;</p><pre>fix: symmetric risk-aversion and wire cash_penalty to fix sell-everything convergence</pre><p>That was an actual commit message. You can tell I was frustrated.</p><p>This one was sneaky. The model learned to buy, learned to hold in the right range, but the sell ratio was literally zero percent. It would buy positions and hold them forever, even when they were losing money.</p><p>The problem was that the action space was asymmetric. Buying creates a new position (positive feedback-the model sees new unrealized P&amp;L signals). Selling just removes a position (the slot goes quiet). There was nothing in the reward function that specifically encouraged realized profit-taking.</p><p>Two fixes, same commit:</p><p><strong>Hold-as-sell symmetry</strong>: Actions in the mild negative range (-0.3 to 0) now count as “hold-as-sell”-a weak sell signal. This gives the model a wider zone for expressing “I’m somewhat bearish on this position” without needing the full conviction of a strong sell signal below -0.3.</p><p><strong>Profit-taking reward</strong>: A direct bonus for closing profitable positions:</p><p>This was the commit that finally got sell ratios above 5%. Not glamorous. But the model needed explicit incentive structure to learn that selling can be good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WrDmk0zTL3-6p23-" /></figure><p>This one ate three days. Training would run for 50–100 iterations, everything looking fine, then suddenly: NaN in the loss, NaN in the gradients, NaN in the weights. Model destroyed.</p><p>The root cause was the TanhNormal distribution. With 25 continuous action dimensions, the log-probability computation involves atanh of the sampled action. If the action is close to -1 or 1 (which happens regularly since we use tanh), atanh produces huge values. Those flow through the PPO ratio calculation ( exp(log_prob_new - log_prob_old)) and blow up.</p><p>The fix was a stack of numerical guards:</p><pre># 1. Clamp log-probabilities to prevent infinite PPO ratios log_prob = log_prob.clamp(- 20, 0) # 2. Clamp individual loss components objective_loss = objective_loss.clamp(- 100, 100) entropy_loss = entropy_loss.clamp(- 100, 100) # 3. Detect NaN in batch and skip the update if torch.isnan(total_loss).any(): optimizer.zero_grad() # Reset optimizer state # Rollback to pre-update weights model.load_state_dict(checkpoint_weights) continue # 4. Scale entropy coefficient by action dimension # Without this, entropy bonus overwhelms the objective with K=25 actions entropy_coeff = base_entropy_coeff / action_dim</pre><p>That last one-scaling entropy by action dimension-was the real insight. Standard PPO implementations use a fixed entropy coefficient (like 0.01). But entropy of a 25-dimensional continuous distribution is way larger than entropy of a single discrete action. The entropy bonus was drowning out the actual policy gradient signal.</p><p>This one was philosophically interesting. PPO uses stochastic policies-the model outputs a mean and standard deviation, then samples from that distribution during data collection. The idea is that randomness drives exploration.</p><p>For a single-action environment, this works great. For 25 continuous actions? The random noise causes the model to simultaneously buy and sell at random, the portfolio churns, transaction costs destroy returns, and the reward signal is pure noise. The model can’t distinguish “my policy mean was good but noise made it bad” from “my policy mean was bad.”</p><p>The fix was deterministic exploration with fixed noise:</p><pre># Instead of sampling from TanhNormal(loc, scale): action = tanh(loc) + gaussian_noise(sigma = 0.05) # The policy mean (loc) directly affects the reward # Small fixed noise provides exploration without destroying signal</pre><p>This was a big philosophical departure from textbook PPO. By using deterministic actions during collection, the reward signal directly reflects the quality of the policy mean. The small Gaussian noise (sigma=0.05) still provides some exploration, but it’s controlled and doesn’t produce the wild swings that stochastic sampling causes in high-dimensional action spaces.</p><pre>fix: use deterministic actions in collector so rewards push policy mean</pre><p>Another commit message that tells a story.</p><p>If you’ve been reading carefully, you’ve noticed a pattern: every convergence failure was fixed by adding or modifying a reward component. The reward function grew from “portfolio return minus benchmark” to an 11-component beast. Here’s what it looks like now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pjfItOahyVHiMkBc" /></figure><p>That “When Active” column is the curriculum schedule-more on that in a second.</p><p>The key insight is that you can’t dump all 11 components on the model from step one. I tried. The gradients are pure noise-the model has no idea which of 11 signals to follow, so it follows none of them. It converges to “hold everything, do nothing” because that’s the only policy that doesn’t violate <em>any</em> penalty.</p><p>The curriculum scheduler progresses along four axes simultaneously, each on a staggered schedule:</p><pre>Iteration: 0 40 80 120 150 180 200 250 280 300 │ │ │ │ │ │ │ │ │ │ Window length: 200 ──────▶ 400 ──────▶ 800 ────────────▶ Full ────── Active rewards: 3 ───▶ 5 ──▶ 8 ────────────▶ 11 ──────────────────── Obs noise: 0.03 ───────────────▶ 0.01 ────────────▶ 0.0 ─────── Learning rate: 0.003 ──────────────────────▶ 0.001 ─────▶ 0.0003 ──</pre><p><strong>Episode windows</strong>: Early training uses 200-step sub-windows randomly sampled from the full time series. The model only sees short chunks-think of it as learning to walk before running. Gradually we extend to 400, 800, and finally the full sequence. This prevents the model from getting overwhelmed by long horizons early on.</p><p><strong>Reward progression</strong>: Start with just 3 components (excess return, churn penalty, extreme action penalty). The model learns the basics: generate alpha, don’t over-trade, don’t go crazy. Then we layer in volatility management, drawdown avoidance, and the more nuanced components.</p><p><strong>Observation noise</strong>: This one is sneaky. Early in training, we add Gaussian noise (std=0.03) to all observations. This forces the model to learn robust features-it can’t memorize specific price patterns because they’re noisy. We anneal the noise to zero by iteration 280.</p><p><strong>Learning rate decay</strong>: High LR early for fast learning on the simpler curriculum stages, decayed for fine-tuning on the full objective.</p><p>The critical detail: these transitions are <strong>staggered</strong>. We never advance two axes on the same iteration. If the window length increases at iteration 80, the reward components don’t change until later. One thing at a time. An early version tried advancing everything together, and the model would destabilize at every transition point-the optimization landscape changed too much at once.</p><pre>fix: stagger curriculum transitions to prevent destabilization</pre><p>The RL model doesn’t train on raw market data. It trains on carefully constructed episode arrays. The pipeline is two phases:</p><p><strong>Phase 1</strong> (parallel, 16 instances): Load scored parquet files, compute 40 technical features per stock per day, write feature-engineered parquets.</p><p><strong>Phase 2</strong> (single instance): Merge everything into dense (T, K, F) arrays. T = number of trading days, K = 25 stocks, F = 40 features. Time-based train/val split (80/20, no lookahead bias). Z-score normalization on features, clipped at 3 standard deviations.</p><p>The output is a .npz file with:</p><ul><li>features: (T_train, 25, 40) - the observation tensor</li><li>returns: (T_train, 25) - daily stock returns</li><li>mask: (T_train, 25) - which stocks are active on each day</li><li>spy_returns: (T_train,) - benchmark returns for excess return calculation</li><li>vix_levels: (T_train,) - VIX for regime-aware position sizing</li><li>sectors: sector labels per stock per day for concentration penalties</li></ul><p>One thing that bit us: some stocks only become active partway through the training period (IPOs, new listings). The mask tensor handles this, but early versions of the environment didn’t properly handle masked stocks in the reward function. The model was getting penalized for “not investing” in stocks that didn’t exist yet. Filtering the subsample to prioritize stocks that are active early in the episode fixed this.</p><pre>fix: prioritize early-active stocks in HPO subsample to prevent zero reward</pre><p>We started on Ray RLlib-the standard choice for RL at scale. It worked. It was also a black box. When training diverged, the debugging story was “add print statements to RLlib’s internal PPO loop” which involves navigating six levels of class hierarchy and a custom execution framework.</p><p>The migration to TorchRL (PyTorch’s official RL library) was motivated by control. TorchRL gives you the building blocks-loss modules, data collectors, replay buffers-but you write the training loop yourself. When something goes wrong, you’re debugging PyTorch code, not framework abstractions.</p><p>The migration took about 3 weeks across several PRs:</p><pre>feat: migrate RL training from Ray RLlib to TorchRL with concert blending fix: MLP out_activation_class not supported in TorchRL 0.11.1 fix: use Bounded instead of deprecated BoundedTensorSpec in tests fix: fully implement TorchRL training - target updates, curriculum, LayerNorm fix: include torchrl_trainer in S3 deploy + fix GPU/CPU device mismatch perf: enable GPU learner + increase env runners for faster RL training</pre><p>The payoff was immediate. When the NaN explosions started (failure mode 4 above), I could add the clamping guards directly in the training loop. With RLlib, that would have required monkey-patching internal loss functions.</p><p>TorchRL also made the stock-parallel architecture straightforward. The ProbabilisticActor wraps any nn.Module that outputs (loc, scale), so swapping the flat MLP for StockParallelActor was essentially a config change.</p><p>I covered the Sortino trap in the previous post, but it’s worth revisiting in the context of RL specifically.</p><p>The HPO system runs multiple RL training trials, each with different hyperparameters, and picks the best one based on an objective metric. For months, that metric was the Sortino ratio on a backtest window.</p><p>The problem: Sortino rewards low downside deviation. The easiest way to have low downside deviation is to not trade. A model that holds 95% cash and makes one tiny profitable trade gets a Sortino ratio through the roof. HPO would find these do-nothing models and crown them champion.</p><p>The composite metric that actually works:</p><p>If excess return is negative (trailing SPY), the composite is negative regardless of Sortino. If Sortino is gaming the denominator to produce infinite values, it’s capped at 3.0. You need both alpha AND risk-adjusted quality to score well.</p><p>We also added deployment gates: buy ratio must be &gt;= 5% (the model actually has to generate buy signals), and backtest return must be &gt;= 0.5%. These seem obvious in retrospect. They weren’t.</p><pre>fix: zero sortino bonus in composite if model isn&#39;t actively trading</pre><p>Looking back at the git log, a few patterns emerge:</p><p><strong>The reward function IS the specification.</strong> Whatever you reward, you get. Whatever you don’t penalize, the model will exploit. I thought I was defining a reward function; really I was writing a specification for portfolio behavior, one edge case at a time.</p><p><strong>High-dimensional continuous action spaces are a different beast.</strong> Most RL research focuses on discrete actions or low-dimensional continuous control. With 25 continuous actions, standard assumptions about exploration, entropy, and convergence don’t hold. You need structural solutions (stock-parallel architecture, deterministic exploration, entropy scaling).</p><p><strong>Curriculum learning isn’t optional for complex rewards.</strong> Trying to optimize 11 reward components from the start is asking the model to solve a 11-dimensional multi-objective optimization problem with noisy gradients. Start simple. Add complexity gradually. Stagger the transitions.</p><p><strong>Numerical stability requires active engineering.</strong> The NaN explosion issue would never appear in a CartPole environment. It only surfaces with high-dimensional TanhNormal distributions under PPO’s importance ratio. You need explicit guards at every potential infinity point.</p><p><strong>The objective metric shapes behavior more than the model.</strong> I spent weeks tweaking architectures when the real problem was that HPO was optimizing the wrong thing. Get the metric right first. Then tune the model.</p><p>The current model (stock-parallel PPO with 11-component curriculum reward) consistently:</p><ul><li>Maintains 30–70% investment levels</li><li>Generates buy AND sell signals (not just one-sided)</li><li>Holds winners longer than losers (holding bonus working as intended)</li><li>Reduces exposure when VIX spikes</li><li>Avoids sector concentration</li></ul><p>Is it beating the market? Sometimes. On good months it generates 2–5% excess return. On bad months it tracks SPY closely without major drawdowns. The Sortino ratio on recent backtests is in the 1.5–2.5 range-not spectacular, but real.</p><p>More importantly, it’s a framework that’s improvable. Each monthly retraining cycle gets warm-started from the previous best model. The curriculum can be extended. New reward components can be added without rewriting everything. The 47 commits got us to a foundation. The next 47 will (hopefully) get us to something that makes consistent money.</p><p>But I’m not going to pretend the hard part is over. Every time I think the model is converged, it finds a new way to surprise me. That’s RL for you.</p><p><em>This is Post 4 of an 8-part series on building a full-stack AI trading application with LLM coding agents. </em><a href="https://gist.github.com/ttarler/78b108f496eff88f9075553c4f8439bd"><em>Previous: Building the ML Pipeline</em></a><em> | </em><a href="https://gist.github.com/ttarler/78b108f496eff88f9075553c4f8439bd"><em>Next: CI/CD and Deployment When AI Writes the Code</em></a></p><p><em>Originally published at </em><a href="https://gist.github.com/ttarler/78b108f496eff88f9075553c4f8439bd"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=121954646f36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building the ML Pipeline: From LSTM Experiments to Production RL”]]></title>
            <link>https://medium.com/@ttarler/building-the-ml-pipeline-from-lstm-experiments-to-production-rl-251ecc998e5a?source=rss-4389f5a6ff54------2</link>
            <guid isPermaLink="false">https://medium.com/p/251ecc998e5a</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Thomas Tarler]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 14:53:20 GMT</pubDate>
            <atom:updated>2026-02-17T14:53:20.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q5EOj_eJ-5DSzgCr" /></figure><p>Go read any ML trading tutorial online. It’s always the same: download some OHLCV data, train a model, show a backtest chart that goes up and to the right, collect Medium claps.</p><p>Nobody talks about what happens when you try to run that model <em>every single day</em>. When you need to retrain monthly without breaking the thing that’s already trading. When the feature your model was trained on doesn’t exist at inference time. When your processing job takes 8 hours and your data is stale by the time training starts.</p><p>That’s what this post is about. Not the model-the machine around the model.</p><p>My first attempt was the obvious one. One model. Market data goes in, trading decisions come out. Simple.</p><p>It didn’t work. At all.</p><p>The problem is that “should I trade this stock?” and “how should I size this position?” are completely different questions. Scanning 8,000 symbols for the 50 worth considering is a classification problem. Random forests eat that for breakfast. But deciding how much to buy given your current holdings, cash, and risk limits? That’s a sequential decision problem. Reinforcement learning fits way better.</p><p>So I split it:</p><pre>┌─────────────────────────────────────────────────────────────────────┐ │ PRESCREENING MODELS (Random Forest + XGBoost) │ │ Input: 8,000+ symbols with 40+ technical features │ │ Output: buy_probability, sell_probability for each symbol │ │ Job: Filter to top 50 candidates │ └─────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────┐ │ RL PORTFOLIO MODEL (PPO/SAC) │ │ Input: 50 candidates + current holdings + prescreening scores │ │ Output: BUY / HOLD / SELL action for each position │ │ Job: Optimal portfolio allocation │ └─────────────────────────────────────────────────────────────────────┘ │ ▼ Order Execution</pre><p>The trick that makes this work: prescreening scores become <em>input features</em> to the RL model. The RL model doesn’t blindly trust the prescreening-it takes those signals and weighs them against technical indicators and current position state before making the final call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F7XfkdyT3vbfbTh2" /></figure><p>Before I built any of this, the system was using something way more “impressive”-LLM agents making trading decisions. Three of them, no less:</p><ul><li><strong>Prescreening Agent</strong>: Analyzed market data, decided what to research</li><li><strong>Portfolio Agent</strong>: Made allocation decisions based on agent discussions</li><li><strong>Risk Agent</strong>: Reviewed decisions for risk compliance</li></ul><p>Sounded like a hedge fund. In reality it was three LLMs arguing with each other at 2 seconds per API call while the market moved on without them.</p><p>Latency was 3–6 seconds per decision. Nondeterministic-same inputs, different trades. Debugging was “which of the three agents decided to buy TSLA?” (Usually the answer was “all of them, sort of.”) Costs were $0.01–0.05 per decision in API tokens.</p><p>Replacing LLM agents with ML models: 200ms decisions, deterministic, $0.0001 per decision. Same quality or better, since the ML model is actually trained on outcomes instead of vibes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ihPuEosaCS1Pl-Ny" /></figure><p>I wasted weeks on LSTMs. The logic seemed airtight: stock prices are time series, LSTMs handle sequences, therefore LSTMs predict stocks. QED.</p><p>Trained one on OHLCV data. Backtests showed 70%+ accuracy on the holdout. Deployed it. Completely useless live.</p><p>The problem was that I was asking the wrong question. My LSTM was answering “Will AAPL go up tomorrow?” when what I actually needed was “Should I buy AAPL vs GOOGL vs MSFT today?” Those are fundamentally different. LSTMs are great at the first one. For the second-cross-sectional ranking with tabular features-tree models just work better. They train in minutes instead of hours and you can actually see which features matter.</p><p>The LSTM code is still in the repo, commented out. A monument to premature sophistication.</p><p>The prescreening models chew through 40+ features. I’m not going to pretend I designed this set on day one-most came from the classic loop of “add features, retrain, check if AUC goes up.”</p><p><strong>The usual suspects:</strong></p><ul><li>Price vs moving averages (SMA20, SMA50, SMA200)</li><li>Momentum (RSI, rate of change, 5/10/20-day momentum)</li><li>Trend strength (MACD, ADX, directional movement)</li><li>Volume (relative volume, OBV slope, VWAP distance)</li><li>Volatility (10/20/30-day, Bollinger bands, ATR, and my favorite-vol of vol, which is a solid regime change indicator)</li><li>Market context (VIX level, VIX change, regime encoding, relative strength vs SPY)</li></ul><p><strong>The newer stuff-fundamentals (6 features):</strong></p><p>These came from a specific frustration: the model kept treating technically similar stocks the same way, even when one was a profitable mega-cap and the other was a cash-burning small-cap. Pure technicals can’t tell you that. We pull the data from Financial Modeling Prep’s API, normalize it, and cache results in S3 with a 30-day TTL. A dedicated pipeline stage grabs sector mappings once and writes a shared sector_map.json so all 8+ processing partitions reuse it instead of each one hitting the API.</p><p>Early RL experiments used weight-based allocation: model outputs a weight per candidate, normalize to sum to 1. Problem: if the model shifts weights, positions vanish. Stock you bought yesterday at 5% allocation? Today the model says 0%. You sell at a loss because the model forgot about you.</p><p>Version 2 uses explicit actions:</p><pre># V1: Weight-based (whipsaw city) # Model outputs: [0.4, 0.3, 0.2, 0.1, 0.0] → allocate 40% to AAPL, etc. # Problem: Holdings vanish if not in top weights # V2: Action-based (much better) # Model outputs: [-0.8, 0.5, 0.1, -0.5, 0.7] in range [-1, 1] # Interpretation: # &gt; 0.3 → BUY (strength proportional to value) # &lt; -0.3 → SELL (only if currently holding) # else → HOLD (do nothing)</pre><p>Now the model has to <em>explicitly</em> say “sell this.” Positions stick around until the model actually wants them gone.</p><p>The model sees 27 features per candidate (grew from 21 recently):</p><p>I got tired of hard-coding [256, 256] hidden layers and hoping that was close enough. The network architecture-hidden sizes, layer norm, activations-is now part of the HPO search space. The optimizer explores [128,128], [256,128], [256,256], and [256,256,128] as categorical options. Architecture metadata gets saved to the checkpoint so inference can reconstruct the exact same topology. One less thing to get wrong at deploy time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hIZvLMOYATCag9CS" /></figure><p>If you train an RL model with raw P&amp;L as the reward, you get a model that chases short-term wins and blows up on drawdowns. Ask me how I know.</p><p>I added three reward shaping components:</p><ul><li><strong>Drawdown penalty</strong>: Quadratic. Gets ugly fast when the portfolio dips below threshold. The model learns that avoiding big losses matters more than chasing small wins.</li><li><strong>Holding period bonus</strong>: Encourages holding winners longer. Without this, the model over-trades like crazy-every iteration is an opportunity to “lock in gains” that would have been bigger if it just waited.</li><li><strong>Momentum alignment</strong>: Small bonus for trading with the trend. Penalizes fighting the tape.</li></ul><p>All three have HPO-tunable coefficients. I don’t hand-tune reward functions anymore. SageMaker finds the balance.</p><p><strong>Prescreening (RF + XGBoost):</strong></p><ul><li>Bayesian HPO, 20 trials per job</li><li>Metric: out-of-time AUC-ROC on a chronological 20% holdout</li><li>No inner cross-validation. I learned this one the hard way-adding 5-fold CV inside each HPO trial meant 12 model fits per trial instead of 2. Low-volatility trials were taking 60+ minutes each. Ripped it out; now each trial takes about 5 minutes. HPO’s own Bayesian search handles exploration just fine.</li></ul><p><strong>RL (PPO):</strong></p><ul><li>PyTorch + Ray RLlib in a custom container</li><li>HPO searches over learning rate, clip parameter, entropy coefficient, all the reward coefficients, and hidden layer sizes</li><li>Backtest evaluation on 60-day validation window (doubled from 30-more data points means less noisy metric estimation)</li><li>30–60 minutes per trial with 8 parallel environment runners on ml.g4dn.16xlarge</li></ul><p><strong>Warm start</strong> was a big recent win. Both prescreening and RL HPO can now start from previous training runs. When a new job kicks off, it auto-discovers up to 5 recent parent jobs and does transfer learning from their best weights. Monthly retraining used to start from scratch every time. Now the model picks up roughly where it left off-converges much faster.</p><p>Each job outputs model artifacts to S3, metrics to SageMaker Experiments, feature importance for interpretability, and architecture metadata so inference knows how to rebuild the network.</p><p>HPO jobs run in parallel. One per regime (low/moderate/high volatility) and model type (buy/sell). A typical run fires off 6+ jobs at once.</p><p>This one took embarrassingly long to figure out.</p><p>The RL HPO was optimizing for backtest_sortino -the Sortino ratio measured over a 30-day backtest window. Sounds reasonable. Sortino penalizes downside volatility while rewarding returns. What&#39;s not to like?</p><p>Everything, it turns out.</p><p><strong>Problem 1: The denominator gaming.</strong> If the model holds 95% cash and makes one tiny trade that doesn’t lose money, the downside deviation is essentially zero. Division by near-zero gives you a Sortino ratio of 25,000. HPO sees that and thinks it found the Holy Grail. In reality it found a model that does nothing.</p><p><strong>Problem 2: No risk-free rate.</strong> The original Sortino calculation used r &lt; 0 as the downside threshold. But with T-bills yielding ~5%, a model returning 2% annualized is <em>losing</em> money in real terms. It shouldn&#39;t get credit for &quot;no downside.&quot;</p><p><strong>Problem 3: 30 data points.</strong> Sortino estimated from 30 daily returns is basically noise. The confidence interval is wider than the estimate itself.</p><p>The fix was a composite objective metric:</p><p>Where excess_return is portfolio return minus SPY return over the same period. This kills three birds:</p><ul><li>Cash-hoarding model? SPY goes up, you don’t. Negative excess_return. Composite is negative. Dead.</li><li>Great Sortino but no alpha? ~0 * sortino = ~0. Also dead.</li><li>Gaming the Sortino denominator? Capped at 3.0. Can’t get infinite credit for zero downside.</li></ul><p>I also fixed the Sortino calculation itself-added the risk-free rate to the downside threshold, used proper sample standard deviation ( ddof=1), set a realistic floor of 1% annualized downside deviation (instead of 1e-6), and hard-capped the ratio at 10.0. And extended the backtest window from 30 to 60 days-twice the data for metric estimation.</p><p>The deployment gates got stricter too. A model now needs:</p><ul><li>Non-negative Sortino and excess return (existing)</li><li>Buy ratio &gt;= 5% (must actually generate buy signals-no cash hoarders)</li><li>Backtest return &gt;= 0.5% (must produce meaningful absolute returns)</li></ul><p>Here’s a fun fact about Bayesian optimization: it needs roughly 10x the number of dimensions in initial trials before it’s meaningfully better than random search. My HPO was searching 24 hyperparameter dimensions with 40 trials. That’s a 1.7x ratio. The Gaussian Process surrogate model couldn’t build a useful response surface-it was basically throwing darts blindfolded.</p><p>The fix was surgical: audit every hyperparameter, keep the ones that actually move the needle, fix the rest at sensible defaults.</p><p><strong>12 parameters I stopped searching</strong> (fixed as static):</p><ul><li>gamma=0.99 - standard for long horizons, searching [0.95, 0.999] added noise</li><li>vf-loss-coeff=0.5 - PPO default, never mattered for trading performance</li><li>num-sgd-iter=10 - standard, not worth a dimension</li><li>All the narrow-range reward coefficients (extreme-penalty, entropy-weight, vol-sensitivity, churn-penalty, holding-bonus-weight, momentum-alignment-weight) - ranges like [0.0001, 0.005] are too tight for the optimizer to exploit</li><li>Structural constraints (max-sector-pct, min-hold-for-bonus) - not learning parameters</li></ul><p><strong>12 parameters I kept searching:</strong></p><ul><li>The heavy hitters: lr, clip-param, entropy-coeff, reward-scale, risk-aversion</li><li>Portfolio construction: max-position-pct, stop-loss-pct, take-profit-pct, target-portfolio-vol</li><li>Risk management: drawdown-threshold, drawdown-penalty-weight</li><li>Architecture: hidden-sizes (categorical-moved from static to searchable)</li></ul><p>With 12 dimensions and 30 trials (reduced from 40-saves ~$48/run), the dimension-to-trial ratio is 2.5x. The Bayesian optimizer can now actually learn which regions of hyperparameter space produce good models.</p><p>The ml.g4dn.16xlarge instance has 64 vCPUs, a beefy GPU, and 64GB of RAM. We were using 2 of those CPUs for environment rollout collection. Two. Out of sixty-four.</p><p>PPO is on-policy: the GPU sits idle waiting for environment data between each training step. With 2 workers collecting rollouts, that’s a lot of idle GPU time.</p><p>Bumped num_workers from 2 to 8 and scaled train_batch_size from 4,000 to 8,000 steps to match. Each worker loads the full multi-asset feature matrix (~200MB), so 8 workers use about 1.6GB-well within the 64GB budget. Going higher risks memory contention without proportional speedup from RLlib coordination overhead.</p><p>Expected result: 2–4x faster per training iteration, cutting trial time from 1.5–2 hours down to 30–60 minutes. Combined with reducing total trials from 40 to 30, total HPO wall-clock time should drop by roughly half.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3vGU5hz_gDGEGGGQ" /></figure><p>What started as a “fetch data and train a model” script turned into a 7-stage orchestrated pipeline. I’m not going to pretend I designed all 7 stages on a whiteboard before writing code. This grew organically as I kept discovering things that needed to happen <em>before</em> training, or <em>after</em> training, or <em>between</em> two things that I thought were adjacent but weren’t.</p><pre>1. Backfill → Fetch new OHLCV data from Alpaca (incremental) 2. Export OHLCV → Aurora DB → S3 (because training reads from S3, not the DB) 3. Feature Comp → Compute technical features from raw OHLCV 4. Processing → Generate labeled training data with VIX/regime context 5. HPO → Bayesian hyperparameter optimization for prescreening 6. Score Gen → Champion models generate buy/sell probabilities 7. RL Pipeline → Train RL model on pre-scored data</pre><p>Each stage depends on the previous one finishing. A Lambda orchestrator tracks state in SSM Parameter Store, EventBridge triggers transitions. If stage 3 fails, stages 4–7 don’t run and I get an SNS alert. That sounds simple, but getting it to actually work reliably was its own project (more on that below).</p><p>Some decisions worth explaining:</p><p><strong>Why does “Export OHLCV” exist?</strong> Because backfill writes to Aurora DB (the live trading system reads from there) but SageMaker Processing reads from S3 (because that’s what SageMaker does). Without this bridge stage, training uses whatever stale S3 data was lying around. I lost a week to this once-ran a full pipeline, got weird results, eventually realized the “freshly processed” data was from four months ago.</p><p><strong>Columnar feature serialization.</strong> Features used to be stored as JSON blobs-one string per row. Deserializing 7 million rows of json.loads() added 3-4 minutes per HPO trial. Multiply that by 20 trials and six jobs, and you&#39;re burning an extra hour just parsing strings. Now we write individual float columns ( feat_*) as Parquet. Old JSON data still works via fallback, but the fast path is the default.</p><p><strong>Sector data gets fetched once.</strong> A dedicated stage grabs sector mappings from FMP and writes them to S3 with a 30-day cache. All downstream processing partitions read from that single file. Before this, every partition was independently hammering the API. Eight partitions, same API, same data. Not my finest design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0zSPIEJN0hUWYNxe" /></figure><p>Computing 40+ indicators across 8,000 symbols was taking forever. I threw three things at it:</p><p><strong>Vectorized the indicators.</strong> The original code was computing rolling means, standard deviations, OBV, true range, and returns with Python for-loops. Row by row. On millions of data points. Rewriting them as pd.Series.rolling() calls and NumPy vector ops ( np.sign(), np.cumsum(), np.diff(), np.maximum()) was the kind of change that makes you wonder why you didn&#39;t do it first.</p><p>For example, the old OBV calculation:</p><p>Same result, roughly 50x faster on a large array.</p><p><strong>Multiprocessing.</strong> SageMaker ml.m5.2xlarge instances have 8 vCPUs. I was using one. Added a multiprocessing.Pool with 6 workers per instance, shared the read-only VIX and SPY data via initializer, and let imap_unordered chew through symbol batches. Instant 4-5x on each box.</p><p><strong>Doubled the boxes.</strong> Went from 8 to 16 SageMaker Processing instances. The math works out cost-neutral: 16 boxes for 1.5 hours costs the same as 8 boxes for 3 hours. Half the wall-clock time for the same bill.</p><p>Net result: ~10x end-to-end. What used to be an overnight job now finishes while I’m still drinking coffee.</p><p>This was maybe the highest-ROI infrastructure change I made. For weeks, every time I changed a line in a training script, I had to wait for a full Docker container rebuild through CI/CD. Ten to fifteen minutes minimum. When you’re iterating on a training script and need to test a fix, that feedback loop will drive you insane.</p><p>The fix: a bootstrap.sh entrypoint that downloads the latest scripts from S3 when the container starts. A small GitHub Actions workflow pushes script changes to S3 in about 30 seconds. Containers only rebuild when actual <em>dependencies</em> change-requirements.txt, Dockerfiles, base images.</p><p>Lambda orchestrators pass SCRIPT_S3_BUCKET and SCRIPT_VERSION to each job. Terraform pins the version for production. Twenty-times faster iteration on script changes. Should have done this on day one.</p><p>Running a 7-stage pipeline with EventBridge triggers exposed concurrency bugs I didn’t see coming.</p><p><strong>The double-trigger problem.</strong> A SageMaker Processing job with 16 instances doesn’t fire one completion event. It fires <em>sixteen</em>. Each partition completing sends its own EventBridge event, which means sixteen concurrent Lambda invocations all racing to advance the pipeline. Solution: re-read SSM state at the top of every stage transition and bail out if someone else already moved it forward.</p><p><strong>The stale-state bug.</strong> The orchestrator would read pipeline state from SSM, compute new config flags, then call start_backfill_job(). But that function <em>also</em> reads SSM state internally-and it was reading the <em>old</em> state before the caller had a chance to save the updates. So it would overwrite the caller&#39;s flags with stale values. Fix: save state <em>before</em> calling sub-functions, not after. Classic race condition, annoying to track down.</p><p><strong>Missing incremental parameters.</strong> The export stage wasn’t getting START_DATE for incremental runs, so it defaulted to exporting everything every time. Months of data, every run. Fix: pass a 90-day lookback date when running incrementally.</p><p>None of this is glamorous. But it’s the difference between a pipeline that quietly works and one that randomly launches duplicate training jobs at 3 AM.</p><p>Here’s a subtle one. The prescreening training script does an 80/20 chronological split for out-of-time validation. But the DataFrame was built by concatenating parquet files from S3, and the concatenation order depended on filesystem enumeration-not timestamps. Some rows from the middle of the time period were ending up in the “holdout” set while future data leaked into the training set.</p><p>The fix was a one-liner: sort by signal_date before splitting. But finding it required staring at the data pipeline for a while and asking &quot;why do the OOT metrics look <em>too</em> good?&quot;</p><p>One model for all market conditions is a bad idea. I train separate prescreening models for three volatility regimes:</p><ul><li><strong>Low VIX (&lt; 15)</strong>: Momentum signals carry more weight</li><li><strong>Moderate VIX (15–25)</strong>: Mean reversion matters more</li><li><strong>High VIX (&gt; 25)</strong>: Everything gets defensive, smaller positions</li></ul><p>At inference time, check VIX, route to the right model:</p><p>This added 3–5% AUC over a single model. Worth the complexity.</p><p><strong>Prescreening:</strong></p><ul><li>Out-of-time AUC-ROC on the chronological holdout. Handles class imbalance, threshold-agnostic.</li><li>Precision at top 50-are the picks actually good ones?</li><li>Deployment gate: AUC &gt; 0.70 or the model doesn’t ship.</li></ul><p><strong>RL:</strong></p><ul><li>Composite score: excess return over SPY times capped Sortino ratio</li><li>Max drawdown and recovery time</li><li>Deployment gates: non-negative excess return, Sortino &gt;= 0, buy ratio &gt;= 5%, backtest return &gt;= 0.5%</li></ul><p><strong>In production:</strong></p><ul><li>Daily P&amp;L vs SPY</li><li>Win rate</li><li>BUY/HOLD/SELL distribution (if it’s 90% HOLD, something is wrong)</li><li>Inference latency (must stay under 200ms)</li><li>Per-stage pipeline timing-so I know when something is taking longer than it should</li></ul><p>If win rate drops below 40% or the system trails SPY by more than 5% over a week, I get an alert.</p><p>This one cost me 6 days of the model doing absolutely nothing.</p><p>Training script expected 18 features. Inference code was computing 3 features and filling the other 15 with zeros. The model received garbage, produced garbage, fell back to heuristics, and nobody noticed because the heuristics also produce trades. Just worse ones.</p><p>The fix:</p><p>Boring. Effective. Would have saved me a week if I’d done it from the start.</p><p>This same lesson came back when I expanded from 21 to 27 features (adding fundamentals). New features need backward-compatible fallbacks for old training data that doesn’t have them-fill with neutral defaults and log a warning, but don’t crash. Feature expansion has to be additive. Break nothing, or break everything.</p><ul><li><strong>Prescreening AUC</strong>: 0.73–0.79 depending on regime</li><li><strong>RL Backtest Return</strong>: 15–20% on validation periods</li><li><strong>Live Win Rate</strong>: ~55–60%</li><li><strong>Outperformance vs SPY</strong>: +2–5% monthly (paper trading)</li><li><strong>Pipeline end-to-end</strong>: ~1.5 hours (down from 8+)</li><li><strong>Script deployment</strong>: ~30 seconds (down from 15 minutes)</li><li><strong>HPO search space</strong>: 12 dimensions (down from 24)</li><li><strong>HPO trial time</strong>: 30–60 min (down from 1.5–2 hours)</li></ul><p>Not hedge-fund numbers. But consistent, fully automated, and getting better each cycle. Warm starts mean each monthly retraining doesn’t start from zero, and the composite objective metric means HPO actually finds models that make money-not just models that avoid losing it.</p><p><strong>Start dumber.</strong> I wasted weeks on LSTMs when Random Forest + basic features would have gotten 70% of the result in a tenth of the time.</p><p><strong>Obsess over feature parity from day one.</strong> Assertions everywhere. Log feature counts on every inference call. Diff training inputs vs inference inputs. The silent mismatches will ruin you.</p><p><strong>Build monitoring before you need it.</strong> I built dashboards after things broke. Should have built them before.</p><p><strong>Don’t start with Docker-baked scripts.</strong> The S3 bootstrap pattern should have been the default from day one. Waiting 15 minutes per iteration during active development is insane in retrospect.</p><p><strong>Don’t add cross-validation inside HPO trials.</strong> Let HPO manage the search. Adding 5-fold CV inside each trial cost me 5–6x compute for zero meaningful improvement. Just use an out-of-time holdout and move on.</p><p><strong>Question your objective metric early.</strong> I ran dozens of HPO jobs optimizing Sortino before realizing it was rewarding the wrong behavior. The metric you optimize is the behavior you get. If your metric rewards doing nothing, your model will do nothing-very efficiently.</p><p><strong>Audit your search space dimensionality.</strong> Bayesian optimization in 24 dimensions with 40 trials is random search with extra steps. Cut the dimensions first, tune the model second.</p><p><strong>Test with production data volumes early.</strong> Training on 100 rows works great. Training on 7 million rows OOMs at 3 AM and you wake up to a Slack message that says “all jobs failed.”</p><p>The ML pipeline works. But “works in backtests” and “works in production” are different sentences with different meanings. Next post: why 94% test coverage didn’t stop a catastrophic production failure-and what kind of testing actually matters.</p><p><em>This is part 3 of an 8-part series on building a trading system with AI coding agents. </em><a href="https://gist.github.com/ttarler/24c8250d441660904537b8aaaaed2051"><em>Previous: From Multi-Agent Chaos to a Single Execution Path</em></a><em> | </em><a href="https://gist.github.com/ttarler/24c8250d441660904537b8aaaaed2051"><em>Next: Why 94% Test Coverage Didn’t Help</em></a></p><p><em>Originally published at </em><a href="https://gist.github.com/ttarler/24c8250d441660904537b8aaaaed2051"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=251ecc998e5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Multi-Agent Chaos to a Single Execution Path]]></title>
            <link>https://medium.com/@ttarler/from-multi-agent-chaos-to-a-single-execution-path-341670a4b979?source=rss-4389f5a6ff54------2</link>
            <guid isPermaLink="false">https://medium.com/p/341670a4b979</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Thomas Tarler]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 19:39:49 GMT</pubDate>
            <atom:updated>2026-02-02T19:39:49.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1-Hq6dJCDH_WnS5e" /></figure><p>Here’s a confession: when I started this project, I was way more interested in building something impressive than something that worked.</p><p>Multiple LLM agents coordinating decisions. A dozen strategies running in parallel. Complex fallback hierarchies. HuggingFace endpoints for model inference. It was beautiful on the whiteboard.</p><p>It was hell in production.</p><p>Picture this: a prescreening agent talks to a portfolio agent, which consults a risk agent, which coordinates with the execution layer, while ten different trading strategies fight for airtime. Meanwhile, three levels of fallbacks kick in whenever something fails (and something always fails).</p><p>The components looked something like this:</p><ul><li><strong>LLM Agents</strong>: Prescreening, portfolio allocation, and risk management agents all chatting through a central orchestrator</li><li><strong>Multi-Strategy Execution</strong>: Ten strategies running concurrently, each with their own logic for when to buy and sell</li><li><strong>HuggingFace Endpoints</strong>: Custom LLM deployments for generating decisions in real-time</li><li><strong>Fallback Cascade</strong>: If agent A fails, try agent B. If B fails, try rule-based logic. If that fails, just give up (quietly)</li></ul><p>I told myself this was sophisticated. I told myself this was what a “real” trading system should look like.</p><p>I was wrong.</p><p>Three weeks in, I’m staring at logs at midnight trying to figure out why the system bought TSLA. Not whether it was a good decision-just trying to trace which damn agent made it.</p><p>Was it the prescreening agent’s recommendation? The portfolio agent overriding that? The risk agent stepping in? Some strategy I forgot I activated? One of the fallback paths?</p><p>The answer was usually “yes.”</p><p>Beyond the debugging nightmare:</p><p><strong>Latency killed me.</strong> Each LLM API call takes 500ms to 2 seconds. Chain three agents together and you’re looking at decision times measured in seconds, not milliseconds. In trading, that’s forever.</p><p><strong>Non-determinism made testing pointless.</strong> Same inputs, different outputs. Same market conditions, different trades. How do you write a test for that? You don’t. You just pray.</p><p><strong>The fallback cascade was a lie.</strong> I thought “graceful degradation” would save me. Instead, I got silent failures. The system would degrade so gracefully that I wouldn’t notice it had stopped working for a week. (That happened. More on that in post 6.)</p><p><strong>Operations was a part-time job.</strong> Five agents, ten strategies, three fallback levels. That’s 150 code paths. Every deployment was a roll of the dice.</p><p>The breaking point came after a seven-day outage. Stop-loss monitoring had silently stopped running. The scheduled task was there, marked as active, looking perfectly healthy in the dashboard. It just… wasn’t executing.</p><p>That night I asked myself: <em>What’s the stupidest architecture that could actually work?</em></p><p>One path. One decision. No agents. No parallel anything.</p><p>The current system is almost boring:</p><ol><li><strong>Premarket screening</strong> identifies candidates at 4 AM</li><li><strong>RL model</strong> (or deterministic fallback) makes buy/sell decisions</li><li><strong>Broker</strong> executes the orders</li><li><strong>Monitor</strong> watches for stop-loss and take-profit</li></ol><p>That’s it. Here’s the actual flow:</p><p>When something goes wrong now, I know exactly where to look. One path means one answer to “what happened?”</p><p>I want to be clear about something: the “fallback” here isn’t a complex decision-making system. It’s a simple decision tree that reads prescreening scores and applies basic rules.</p><p>The active strategy just holds risk parameters-stop-loss percentage, position sizing limits, take-profit targets. It’s a config container, not a decision-maker.</p><p>The position monitor runs every couple minutes and does exactly one thing well:</p><p>That await db.commit() before the API calls? Learned that one the hard way. Holding database connections open while waiting for external APIs is a great way to exhaust your connection pool.</p><p>Nothing exotic here:</p><ul><li><strong>Backend</strong>: ECS Fargate running FastAPI</li><li><strong>Workers</strong>: Celery for scheduled tasks</li><li><strong>Database</strong>: Aurora PostgreSQL</li><li><strong>Cache</strong>: ElastiCache (Redis)</li><li><strong>ML</strong>: SageMaker for training and inference</li><li><strong>Scheduling</strong>: EventBridge to trigger everything</li></ul><p>The deployment is GitHub Actions pushing to ECR, then rolling ECS updates. Every deployment includes a manual check of the logs to verify things are actually working. (Yes, I verify. Every time. I’ve been burned too many times.)</p><p>Debugging is trivial now. When a trade happens, I check one log line: “RL made decision” or “fallback made decision.” Done.</p><p>Testing is possible again. I can write an end-to-end test that goes from watchlist to broker call. It runs in seconds. It’s deterministic.</p><p>Operations went from constant firefighting to occasional monitoring. I check dashboards maybe twice a day instead of babysitting alerts constantly.</p><p>Performance improved, weirdly enough. A single SageMaker call takes 200ms. The old multi-agent coordination took 2–3 seconds minimum. Simpler is faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rMAfTKD7ezULcKWb" /></figure><p>Sophistication is a trap. The most impressive architecture is often the hardest to run. I was so focused on building something that looked like “real AI” that I forgot the goal was to make money trading, not to impress other engineers.</p><p>Start with the dumbest thing that could work. If your ML model isn’t ready, use rules. If your rules aren’t ready, just log what you would have done. Get the pipeline working first. Make it smart later.</p><p>Every code path you add is a code path you have to maintain, test, monitor, and debug at 2 AM when it breaks. I went from 150 code paths to 2. My stress levels dropped accordingly.</p><p>When something works reliably, resist the urge to complicate it. I kept waiting for the moment when the simple approach would fail and I’d need the sophistication. That moment never came. The simple path just… keeps working.</p><p>In the next post, I’ll cover how I manage LLM context so Claude doesn’t forget all these hard-won lessons every time a conversation ends. Turns out that’s its own challenge.</p><p><em>This is part 2 of an 8-part series on building a trading system with AI coding agents. </em><a href="https://gist.github.com/ttarler/ce434502be3bb7caa4816f42257d0e72"><em>Part 1: I Built a Full-Stack AI Trading App with LLMs-Here’s What I Learned</em></a></p><p><em>Originally published at </em><a href="https://gist.github.com/ttarler/ce434502be3bb7caa4816f42257d0e72"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=341670a4b979" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Full-Stack AI Trading App with LLMs]]></title>
            <link>https://medium.com/@ttarler/i-built-a-full-stack-ai-trading-app-with-llms-52f9cc235321?source=rss-4389f5a6ff54------2</link>
            <guid isPermaLink="false">https://medium.com/p/52f9cc235321</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Thomas Tarler]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 01:48:41 GMT</pubDate>
            <atom:updated>2026-01-27T01:48:41.262Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Built a Full-Stack AI Stock Trading App with LLMs</h3><p>As a professional data scientist, I’ve spent years building ML models in Jupyter notebooks. But I wanted to go beyond research. I wanted to deploy a full-stack, production-grade AI trading system using my ten years of experience as a product data scientist in payments systems. The catch? I needed to supplement my data science expertise with full-stack development, infrastructure, and operations knowledge I didn’t have. This project enabled me to synteheize much of my existing data science and technical systems design into a working product. That includes managing risk in technical design, building compliance systems to ensure that I did not trade in stocks I’m not allowed to trade, and otherwise securing a system.</p><p>Enter AI coding agents.</p><p>Over the past few months, I used LLMs (primarily Claude via Cursor) to build an automated trading system from scratch: FastAPI backend, Celery workers, Next.js frontend, PostgreSQL database, AWS infrastructure (ECS, SageMaker, EventBridge), and a complete ML pipeline for training and deploying models.</p><p>This series documents what I learned. Not just the technical wins, but the expensive failures, the operational surprises, and the patterns I wish I’d known from day one.</p><h3>What I built</h3><p>Here’s the system architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qGt3CGTqepbdMLQ4zpYSEw.png" /></figure><p>The system runs autonomously. Each morning at 4 AM, ML models analyze technical indicators to generate a watchlist of 50 candidate stocks. During market hours, a reinforcement learning model (trained on SageMaker) decides which positions to open, size them appropriately, and when to exit. If the RL model is unavailable, a deterministic decision tree takes over using predefined risk parameters.</p><p>The stack:</p><ul><li>Backend: FastAPI (Python, async) + SQLAlchemy + PostgreSQL (Aurora)</li><li>Workers: Celery + Redis for scheduled tasks</li><li>Frontend: Next.js (React/TypeScript) dashboard</li><li>ML: SageMaker (training, hyperparameter optimization, inference endpoints)</li><li>Infrastructure: AWS (ECS/Fargate, EventBridge, ALB, ElastiCache), Terraform</li></ul><p>This isn’t a portfolio of ML models. It’s a production system with deployment pipelines, monitoring, runbooks, error handling, and all the operational concerns you’d expect from a real service.</p><h3>Does it actually work?</h3><p>Here’s the week of January 20–24, 2026 (paper trading):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyUjCrXNnhkHRnLoE8hBLA.png" /></figure><p>This is paper trading, not live money. But it proves the system works end to end: the ML models make decisions, positions open and close, stop-losses trigger, and the infrastructure runs reliably. The real test will be longer time periods and eventually live trading with real capital.</p><h3>The Shift: From Coding to Context, Verification, and Operations</h3><p>Here’s the surprising part: LLMs accelerated coding dramatically, but coding wasn’t the bottleneck.</p><p><strong><em>What LLMs did well:</em></strong></p><ul><li>Scaffolding: API routes, database models, Celery task boilerplate, Terraform modules</li><li>Fill-in code: Converting requirements to implementations, writing SQL queries, creating CI/CD workflows</li><li>Documentation: Generating initial docs, README files, deployment procedures</li><li>Debugging: Suggesting fixes for errors, explaining stack traces, proposing alternative approaches</li></ul><p><strong><em>What LLMs struggled with:</em></strong></p><ul><li>Context management: Sessions end and agents forget. Without structure, they repeat mistakes or ignore critical patterns.</li><li>Verification: Agents would claim features were “deployed and working” without checking if they actually worked in production.</li><li>Operations: Understanding that “scheduled” does not mean “working,” that containers need restarting, that metrics matter more than code.</li><li>Integration: Ensuring training and inference use the same features, that tests verify behavior not just execution, that deployments are actually running new code.</li></ul><p>The real bottleneck became managing LLM context, verifying deployments actually worked, building operational discipline, and establishing patterns that prevented recurring failures.</p><h3><strong>The Expensive Lessons</strong></h3><p>Over the course of this project, I encountered failures that cost hours, days, and in one case, rendered an ML model completely useless for a week. I am a data scientist by training and not a MLOps engineer — much of this was lessons for me to learn the ropes and better understand how to turn a great “model” into a fully working application. If you are also a data scientist looking to do fully funcitonal apps, this series is for you. Here are the themes that emerged.</p><h4>1. “Scheduled” Does Not Mean “Working”</h4><p>A Celery task can be perfectly scheduled every 2 minutes and fail every single time. Stop-loss monitoring ran for 7 days without closing a single position. 83 positions accumulated, 30:1 BUY:SELL ratio. Why? I checked scheduler logs but not worker logs.</p><p><em>Lesson</em>: Check outcomes and worker logs, not just schedules.</p><h4>2. Tests that lie</h4><p>94% test coverage. All tests passing. System completely broken in production. Why? Tests verified execution (task returns success) not behavior (positions actually close).</p><p><em>Lesson</em>: Integration tests beat unit tests for critical paths. Test behavior, not just code execution.</p><h4>3. The ML Model Was “Live” for 6 Days But Never Made a Single Decision</h4><p>The RL model was deployed and the agent reported “working.” In reality: feature mismatch (18 features in training, 3 at inference), silent fallback to heuristics, zero real predictions for 6 days.</p><p><em>Lesson</em>: Training-inference feature parity is non-negotiable. No silent fallbacks. Verify models are actually called.</p><h4>4. Committed Code Does Not Equal Running Code</h4><p>I’d commit a fix, push to GitHub, and assume it was running. It wasn’t. Docker containers kept old code until restarted.</p><p><em>Lesson</em>: Always restart affected services. Check logs. Verify the new code path is executing.</p><h4>5. Context is a Product</h4><p>Without structured documentation, LLM agents repeat mistakes across sessions. I built CLAUDE.md, AI_AGENT_QUICK_REFERENCE.md, and .ai-knowledge-base.yaml to encode patterns, anti-patterns, and verification steps.</p><p><em>Lesson</em>: Treat agent context as a first-class deliverable. Single source of truth beats ad-hoc instructions.</p><h3>What’s Coming in this Series</h3><p>This introduction sets the stage. The rest of the series dives deep into each lesson:</p><p>Post 2: Architecture Evolution (From multi-agent chaos to a single execution path)</p><p>Post 3: Managing LLM Context (How I structured docs so agents don’t forget critical patterns)</p><p>Post 4: Why 94% Coverage Didn’t Help (Testing behavior vs execution, integration vs unit tests)</p><p>Post 5: CI/CD with AI-Written Code (Deployment discipline, verification policies, runbooks)</p><p>Post 6: The ML Model That Never Ran (Feature parity, no silent fallbacks, end-to-end verification)</p><p>Post 7: “Scheduled Does Not Mean Working” (Operational assumptions, metrics that matter, async+DB patterns)</p><p>Post 8: Proof It Works (A week of paper trading performance vs S&amp;P 500)</p><p>Each post includes real code snippets, anonymized mishaps, and actionable practices you can adapt.</p><h3>Why this matters for data scientists</h3><p>If you’re a data scientist looking to ship production ML systems (not just notebooks), AI coding agents can accelerate your journey. But they introduce new failure modes. The bottleneck shifts from “can I write this code?” to “can I verify it works, maintain context across sessions, and operate it reliably?”</p><p>This series is for data scientists who want to use LLMs as force multipliers while avoiding the expensive lessons I learned. It’s also about strengthening your professional brand: demonstrating you can think in systems, not just models.</p><h3>Lets go</h3><p>Over the next 7 posts, I’ll walk through the architecture, the failures, the patterns, and the proof that it works. The goal isn’t just to document what I built. It’s to help you build better.</p><p>Ready? Let’s start with how the architecture evolved from multi-agent chaos to a single, testable execution path.</p><p>This is Post 1 of an 8-part series on building a full-stack AI trading application with LLM coding agents. Next: Architecture Evolution.</p><p><em>Originally published at </em><a href="https://gist.github.com/ttarler/2540b3b7342926533525f7f30d03b83d"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52f9cc235321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What IS Data Science?]]></title>
            <link>https://medium.com/@ttarler/what-is-data-science-c7ae5a046860?source=rss-4389f5a6ff54------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7ae5a046860</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[epistemology]]></category>
            <category><![CDATA[decision-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Thomas Tarler]]></dc:creator>
            <pubDate>Tue, 25 Aug 2020 21:01:00 GMT</pubDate>
            <atom:updated>2020-08-25T21:01:00.917Z</atom:updated>
            <content:encoded><![CDATA[<p>If you ask a thousand data scientists what data science is, you will get a thousand different answers. Granted, there is writing ad nauseam trying to define the field. Still, while there is agreement on the subject matters necessary and methodologies utilized, generally, the most straightforward and most concise answer is “I know it when I see it.” Data science is elusive in these definitions as is it is to define. There is no theory of data science, no centralized understanding of the nascent field primarily because it has developed rapidly in the prior decades that no successful attempt has aimed to synthesize and generalize knowledge in the field. In this article and further iterations, I will attempt to add some structural context, to answer two broader questions:</p><ol><li>What is it that data scientists know?</li><li>How do they know it?</li></ol><p>My argument is that data scientists know how to create self-consistent and generating knowledge systems, of how to compute knowledge and actions independently of human consciousness. The loaded term for this is artificial intelligence, both of a specific and general nature. Our methods are what I will characterize as hyper-empirical, in that we create and use observations often without connection to an underlying theory. Data Science is different, as most epistemological approaches have focused on how we as humanity know something often concerning some absolute truth divine or not. Our models are usually but not necessarily reflect the real world, and this is an important distinction to make.</p><p>This first article will focus simply on why having a theory of data science is essential. Further, these articles will focus on the history of computing and data science, the differences and similarities with areas of knowledge, and methods of study that we borrow from. We must then approach what data science’s methods of knowledge are and how they may combine into AI systems. There are many ethical and professional issues to explore as well, which will be integrated throughout.</p><p>Before we move on to our primary objective, it is worth speaking about the general audience and making some necessary caveats. These articles are not a series about how to do data science, but rather a proposal of how to think about data science. While I will likely integrate examples from my professional and personal experience, the target here is towards experienced practitioners.</p><p><strong>Motivation</strong></p><p>With the introduction out of the way, let’s move on to our motivation. We start with the traditional definitions of the field: Data science is the intersection of mathematics, computer science, and economics (or another social science). We use large volumes and varieties of data, often at high velocities to classify, label, predict, group, or otherwise understand phenomena. These methods typically fall into two groups, supervised learning (where a system imitates past classifications or predictions) and unsupervised learning (where a system establishes its own labels and predictions). A newer technique is reinforcement learning, where a strategy or policy is created in order to achieve a longer-term goal. The scientific method is intrinsic to our methods; we use evidence to demonstrate the success or failure of a system. These describe what a data scientist does, but not necessarily why or how. Often though, the actual “why” for a result is left far behind. We do not create knowledge hypotheses to test or theories to be nullified, a central feature of science, and epistemological work overall. We do often utilize hypothesis testing for evaluating a specific insight, but this is not necessarily what data scientists produce.</p><p>Take neural networks, a black-box algorithm that can approximate almost any function. This algorithm works but interrogating how they work and why they work to solve a particular problem is nigh impossible. We can understand that a computer image system may use certain features to classify, but the reasoning why is opaque. This contrast leads to a central issue in the field and one where we diverge most significantly from other realms of human knowledge; data science cares less of truly understanding a system and more about demonstrating that the understanding is there. We do not care much about showing how we know, but rather why this system can be said to know. We are scientists only in the way we collect and analyze, but not in the ways we synthesize or generalize.</p><p>If we are not scientists, then are we at least mathematicians? We do take existing mathematical algebras and systems and apply them to new problems to see if and how they work. Our problem solving can involve work around checking assumptions and behavior around making a calculation. Yet we do not make proofs; we cannot show that in every situation with the same set of assumptions that a result is consistent or replicable. Indeed, we do not make general theories and definitions that predict how well a model or a system will do. Instead, we take our understanding of a system and apply it to a new problem to be solved. We work hard to show general consistencies within a problem solution, but we fail to be mathematicians in showing a general solution for all problems of this type. Indeed, because problems have different types of data as inputs, this would be impossible; we cannot generalize and create axioms.</p><p>If we are neither scientists nor mathematicians, perhaps an artist is the appropriate label. We are generative and creative; we take a new problem and apply different approaches and experiments to find what is best. We dive down into the theories and assumptions that we are making to understand but typically only in the scope of the problem. The mark of a brilliant data scientist is not that they are excellent mathematicians or programmers or economists but rather that their natural curiosity leads to new approaches to solving problems. Many times a problem may not have the best solution to it but rather the best approach; science and mathematics have easy objective ways of evaluating the fit of an approach, but data scientists have a qualitative evaluation more similar to art. We express new ideas of understanding and framing phenomena that already exist but may be beyond other approaches. A social scientist can measure the angst of a moment in human history and theorize about its causes, but it is the artists of that era that capture it. The systems a data scientist creates are not necessarily locked to a given past understanding — unsupervised learning can yield clusters humans could not have come to otherwise. Indeed an AI system can write text or create a deepfake video indistinguishable from the human-curated form. Yet artists, even with their flexibility, still have a theory to their art. A musician uses tonal scales to make music that sounds good; a painter must have a color theory to create a striking piece.</p><p>An artist can have immense impacts on the social-cultural fabric of a people but rarely impact the individual lives of those living. In contrast to artists, the impact of data science can make immensely impactful decisions from the economic sphere to business decisions, a tension that creates a need for a theory of data science. A medical doctor must recommend treatments that are empirically validated and theoretically understood, and we mandate this because otherwise, they may cause deaths and human suffering. Data Science without an underlying theory of practice or professional rigor and ethics potentially yields much more catastrophic consequences. Effort and rigor must go into what we do, how we know it was right, and the resulting effects.</p><p><strong>So whats next?</strong></p><p>What we create are decision systems, ones that may not necessarily be fully understood. We utilize mathematics to ensure consistency, science to ensure generalizability and are creative artists with the design and approach. Whether a simple decision tree or a deep deterministic policy gradient the heuristics of the system itself matters far less than the understanding of the systems performance. The outcomes of these systems are what matter most, and where our epistemological foundations lie.</p><p>What I have not answered as of yet is why this is unique in the past history of human knowledge. In the next article, we will explore why data science arises from computer systems and the internet rather than design them and the implications towards our practice before doing some more in-depth analysis of the underlying connections and theories first expressed here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7ae5a046860" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Dynamics and Training Data sets]]></title>
            <link>https://medium.com/@ttarler/system-dynamics-and-training-data-sets-bd88aa068a67?source=rss-4389f5a6ff54------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd88aa068a67</guid>
            <category><![CDATA[data-wrangling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[full-stack-data-science]]></category>
            <dc:creator><![CDATA[Thomas Tarler]]></dc:creator>
            <pubDate>Mon, 22 Jul 2019 16:49:59 GMT</pubDate>
            <atom:updated>2019-07-22T16:49:59.832Z</atom:updated>
            <content:encoded><![CDATA[<p>A recent trend in the data science community has been the conversation around curating and wrangling a data set. In the enterprise world, data will never be as clean as in a Kaggle competition or the training data we use in school. Skills to handle these situations are vital to a data scientist but the true solution is to ensure valid data sets are created in the first place. In a conversation about Ben Taylor’s recently published <a href="https://towardsdatascience.com/ai-is-begging-for-better-data-70c4b27387c9">article</a> a mutual contact remarked that the true investment into AI technologies is in creating the correct data sets. Any data scientist will tell you that having a well curated data set with accurate labels is far more important than having a good algorithm. No amount of sampling or imputation can fix a data set that has been poorly maintained — it is better to invest in creating a new data set than attempting to create a semi-viable model. Within data science the vast majority of value is often derived from a regression or classification problem on a labeled data set, otherwise known as supervised learning. Supervised learning is vital to deriving business value because it delivers a prediction towards the future that a business can take action on. This contrasts with unsupervised learning where certain structural properties may be derived but are much harder to put into practice. We will focus on labelled training sets particularly in the world of credit card transaction fraud, and how best practices there might be synthesized into other industries and use cases. This article will focus heavily on the need for a business domain expertise as part of the data science process and how to create effective incentives for data set tagging.</p><p>First some background on what happens when a transaction is marked suspicious, usually via business rules utilizing fraud scoring. The transaction will go into a queue to be worked. The bank will then reach out to the cardholder directly to determine if the transaction was genuine. Once the cardholder has indicated the transaction is fraudulent, the bank will then collect more information from them to determine other possible fraudulent transactions, block and transfer the credit card, and begin trying to recover funds. The bank will often file a police report, send further information back to the credit card network for network analysis and work with a merchant to recover any lost funds. Sometimes a transaction will not be considered suspicious and only be marked as fraud when the cardholder reviews their bank statement.</p><p>This system has several particular characteristics that we need to bear in mind when we create machine learning models. It can take up to 40 days for a transaction to be marked fraudulent so you must only use training and testing data that has had frauds “matured”. Additionally, the system is relatively expensive — between call center costs, cardholder messaging, and recovery every fraudulent transaction will cost approximately $5 to work and that’s before you consider any money that has been defrauded. The net result is an excellent quality training data set — fraud labels will be extremely accurate because the system requires that every stakeholder to be absolutely certain. The cardholder will never want to pay for transactions they aren’t responsible for. A bank will want to reduce its fraud losses in order to improve profit and may have other regulatory pressures to respond to. Merchants have an incentive to ensure that non-fraud transactions are not charge-backed to them, and the card brand networks want to ensure an efficient and trustworthy network. Certainly this system was never intended to create a robust training set yet one evolved under the right conditions, yet everyone wins when this properly tagged data set is created.</p><p>This system breaks down once we move to other types of fraud with different types of incentives. One is application fraud or identity theft, where a fraudster will use a stolen or synthetic identity to obtain a credit line. They will often use the credit card normally for several months to build up a pattern of genuine behavior and spoof existing fraud algorithms. Since the person being defrauded often is unaware of this behavior until their credit score tanks there will be a significant delay for the fraud to be noticed and marked correctly. Banks are likely to label this fraud as a bankruptcy and charge-it off. No merchants are impacted. As a result the application fraud dataset has a much longer delay and the markings will not have the same robustness.</p><p>A similar activity that is hard to detect is “friendly fraud” when a cardholder disputes a charge that they themselves are responsible for. Again, the behavior of the transactor is genuine so traditional fraud algorithms will not work here. The network is constructed to protect the cardholder so a merchant may have to collect additional evidence to override these claims. When this occurs and the fraud is not caught, the data set will contain fraud labels on legitimate genuine transactions which will confuse any training data sets. In both of these examples, a viable strategy to win these fraud “games” need not incorporate fraud tagging.</p><p>Throughout this piece I’ve alluded to this system as a game, where players gain a reward by taking correct or incorrect actions that incidentally create the data sets that we are looking for. Mathematically a game is a situation where one or more agents engage in a strategy that allocates some resource — establishing the correct strategy to maximize profit for an arbitrary agent is the central problem. This paradigm works well for considering how to create well-tagged data sets. Credit card fraud has a high transaction cost for any given action, typically around $5 per fraud transaction worked. The reward of the credit card transaction system mitgates this. Still any system can create incentives for a well tagged data set. For instance, in the case of consumer segmentation, aligning incentives and systems for consumers to “self-identify” will help businesses better target them. Netflix is an excellent instance of this, the more a user rates the content they consume the better the recommendations they see for additional content. Another instance is a data science firm that specializes in fusing public data sets with internal data. In some instances they have collected additional data from their customers employees (with full and informed consent) as a way to validate the accuracy of the data sets they are bringing in. Asking someone for their home value is often far more accurate than imputing this attribute from other data sources. An allegory I have heard is a Google executive claiming that they do not create Artificial Intelligence — they create excellent training data sets.</p><p>With the importance of data as an input, the impetus comes with creating a system to curate those data sets. This is not a simple problem; the interaction of many different data sources and inputs leads to a complex, non-linear system. Modelling out this system and figuring out how to manipulate it to create a good data set will become a vital capability for any data-savvy company. Start-ups and new industries can create these systems from scratch (see: FAANGS); what will enable legacy enterprises to survive is the ability to adapt old ecosystems with inertia to create well-tagged data sets. This is partially why so many reinforcement learning tasks are prototypes on computer games — the structure of the game itself ensures that robust data sets are generated. Furthering the issue is that there are many data science problems to be asked of a single data set; the system creating the data needs a form of Turing-completeness to create a data set that an arbitrary number of classification and regression problems can be asked of. Game theory would be one solution to solving this systematic problem. A win-loss function can be tuned such that the optimal strategy of any player is to create a Turing-complete data set.</p><p>A final observation: data scientists need to train themselves on these skills to ensure they are not wrangling data sets from the start. Engaging in the pain of cleaning a data set from the start is an important lesson for any data scientist. Many companies assign this task to junior data scientists, perhaps burning them out and preventing them from seeing the “cool” parts of data science. Rather the emphasis should be on creating the right systems and incentives to create proper training sets from the start. Reinforcement learning paired with game theory offers a strategy for achieving this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd88aa068a67" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>