
How We Made Our ML Prediction Engine 12x Faster (Without Cutting Corners)
Our ML pipeline was taking 25+ seconds to generate signals. After weeks of profiling and rewriting core systems, we got it under 2 seconds.
We rebuilt Nydar's ML prediction pipeline from 25+ seconds per request down to under 2 seconds — a 12x improvement — without reducing analysis depth, cutting symbol coverage, or upgrading hardware. The gains came entirely from eliminating redundant computation and restructuring how data flows through the system.
There's a dirty secret in trading platforms that use ML: most of them are slow. Not "could be faster" slow — genuinely, painfully slow. The kind of slow where you click a button and wonder if the page crashed.
We had this problem. Our daily picks, market analysis, and morning briefing endpoints were taking 25+ seconds on a cold cache. For a platform that's supposed to help you make timely trading decisions, that's unacceptable. You'd click "Daily Picks" and have time to make a cup of tea before the results appeared. That's not a user experience — that's a test of patience.
The really frustrating part? The actual predictions were good. Our 13,500-model-fit research had produced models with genuine predictive power. The ML side was working. But none of that matters if users give up and close the tab before the results load. According to Google's Core Web Vitals research, 53% of users abandon a page that takes longer than 3 seconds to load — and our 25-second endpoint was losing users who'd never even see the predictions (Google Web Performance, 2023).
We could have thrown hardware at it. Spun up bigger servers, added GPU instances, horizontally scaled across a cluster. That's the standard playbook — and it's what most platforms do. But that's not engineering — that's spending money to avoid thinking. Bigger hardware doesn't fix a fundamentally inefficient architecture. It just makes the inefficiency more expensive.
We wanted to understand why it was slow and fix the actual problem.
That turned into weeks of work. Multiple failed approaches. A complete rewrite of core systems. What we found was worse than we expected — and the fix required rethinking how our entire prediction pipeline was built from the ground up.
What Does the ML Pipeline Actually Do?
Before digging into the optimisation, it's worth understanding the sheer scope of what happens when you load the Daily Picks page. This isn't a database query. There's no pre-computed table of recommendations sitting on a server. Every signal is generated in real-time from live market data, every time you load the page.
For each of the 55+ symbols we track across crypto and equities, the system runs this full analysis pipeline:
-
Multi-timeframe data fetching — pulls OHLCV (open, high, low, close, volume) candles across four timeframes: 15-minute, 1-hour, 4-hour, and daily. Each timeframe tells a different story about price action, and you need all of them to form a complete picture.
-
Technical indicator computation — calculates dozens of mathematical indicators across momentum (RSI, Stochastic RSI, CCI, Williams %R), trend (ADX, EMA crossovers, MACD), volatility (ATR, Bollinger Bands, Keltner Channels), volume (OBV, VWAP, MFI), and price action (candle body ratios, wick analysis, pattern detection).
-
ML feature extraction — transforms raw indicators into normalised, model-ready features. Features need to be scaled relative to price, normalised across different volatility regimes, and structured to capture the relationships between indicators.
-
Sentiment integration — for crypto assets, the system ingests Fear & Greed Index data, computes moving averages, zone classifications, contrarian signals, and divergence metrics. Sentiment features turned out to be among the most predictive in our research.
-
Market regime detection — classifies the current market environment into one of six states: trending up, trending down, ranging, volatile, breakout, or consolidating. Each regime has different implications for how predictions should be interpreted and which trading strategies are appropriate.
-
Model loading and inference — loads the pre-trained XGBoost model for each symbol-timeframe combination and generates probability distributions across bullish, bearish, and neutral outcomes. The model was trained using walk-forward validation on 2,000+ candles.
-
Meta-labeling — a secondary model that acts as a quality gate. It evaluates whether the primary prediction is reliable enough to act on, filtering low-quality signals to neutral. We wrote about the theory behind this in our meta-labeling deep dive.
-
Multi-timeframe alignment — analyses whether the 15-minute, 1-hour, 4-hour, and daily timeframes agree on direction. A bullish signal on the 1-hour chart means very little if the daily and 4-hour are screaming bearish. The alignment score quantifies this cross-timeframe consensus.
-
Confidence scoring and ranking — combines all signals into a final confidence score, applies regime-aware adjustments, ranks all symbols, and generates natural-language explanations of why each pick was selected.
That's nine distinct computational stages for each of 55+ symbols. A single Daily Picks request triggers well over 400 individual analyses.
Why Do ML Trading Platforms Run So Slowly?
Most ML-powered trading platforms are slow because they compute features redundantly across separate system modules, fetch the same market data multiple times, and process symbols sequentially rather than in parallel. The bottleneck is almost never the model inference itself — XGBoost predictions take single-digit milliseconds — but the data preparation and feature engineering that happens before inference.
This matches broader industry research. A 2022 paper by Paleyes et al. in Patterns found that data preparation and feature engineering consume 60-80% of total computation time in production ML systems, while model inference typically accounts for less than 5% (Paleyes et al., 2022, Patterns).
In our case, it was even worse than that. 98% of per-symbol time was in feature extraction and regime detection — and the two systems were computing the same indicators independently.
The False Starts
Before we found the right approach, we went down several dead ends.
"Just cache everything." Cache the predictions for longer, and most requests will be instant. The problem: caching doesn't solve the underlying issue, it hides it. The first user to hit an expired cache still waits 25 seconds. Caching is a complement to fast computation, not a substitute for it.
"Analyse fewer symbols." Why scan 55 symbols when you could scan 20 and be 3x faster? Because the whole point of daily picks is breadth. You want the system to find the best opportunities across a wide universe. Restricting to 20 symbols means potentially missing the best trade of the day because it was symbol #21. Users trust us to do the full scan — that's the product.
"Pre-filter with a cheap heuristic." Run a quick, rough analysis first, pick the top 10 candidates, then only run the full pipeline on those 10. Sounds clever. But the cheap heuristic ranks symbols differently than the full pipeline would. You end up with a fast system that gives worse answers. We tried this, saw how the candidate lists diverged from the full analysis, and scrapped it.
"Switch to a GPU server." Our models are XGBoost, not deep learning. XGBoost doesn't benefit from GPU acceleration for inference — prediction on a trained model is a series of tree traversals, not matrix multiplications. A GPU would have made no measurable difference.
Each dead end taught us something: the solution had to be architectural, not infrastructural.
Phase 1: Profiling — Measuring Before Cutting
With the quick fixes exhausted, we did what we should have done first: measured.
The instinct when something is slow is to guess where the time goes. Everyone had a theory. Every theory felt plausible. And every theory was wrong. According to research by Knuth and cited in virtually every performance engineering textbook, developers correctly identify the bottleneck less than half the time — our intuitions about code performance are shaped by what feels expensive rather than what is expensive (Knuth, 1974, Structured Programming with go to Statements).
We instrumented the entire pipeline with high-resolution timing markers at every stage. Not just endpoint-level timings — we measured each individual step within each symbol's analysis independently, with microsecond precision.
What We Expected
- Network I/O would dominate — fetching live data from exchanges
- Model training would be expensive — fitting XGBoost on 2,000+ candles
- Database/disk operations — loading cached models, reading configuration
What We Actually Found
| Stage | Time Per Symbol | % of Total | |-------|----------------|------------| | Feature extraction | ~1.3s | 47% | | Regime detection | ~1.4s | 51% | | Fear & Greed fetch | ~0.03s | 1% | | Model loading | ~0.01s | <1% | | XGBoost inference | ~0.002s | <1% | | Meta-labeling | ~0.001s | <1% | | Everything else | ~0.02s | <1% |
The API calls were fast. Model inference was essentially instantaneous. Network I/O was not the bottleneck. Disk access was not the bottleneck.
98% of the time was spent in two systems: feature extraction and regime detection. Specifically, the heavy numerical computation that turns raw price data into mathematical indicators — ATR, Bollinger Bands, ADX, EMA crossovers, RSI, MACD, CCI, Stochastic RSI.
And then came the real insight — the one that made us want to put our heads through the desk.
We were computing many of the same indicators multiple times per symbol. Feature extraction computed RSI, ATR, Bollinger Bands, EMA20, EMA50, ADX. Then regime detection computed RSI, ATR, Bollinger Bands, EMA20, EMA50, ADX again, completely from scratch, because it was a separate system that didn't know what feature extraction had already done.
For 30 crypto symbols, that's 180 redundant indicator computations per request. Each one taking 50-200ms. The duplication alone accounted for nearly 15 seconds of wasted computation.
The irony is that the code was well-structured. Feature extraction was a clean, self-contained module. Regime detection was a clean, self-contained module. By every software engineering principle, the architecture was correct. But the performance characteristics were catastrophic, precisely because those clean boundaries prevented the systems from sharing work.
Phase 2: Data Layer Redesign
With profiling data in hand, we attacked the problem layer by layer.
The original implementation fetched data serially by symbol, then serially by timeframe within each symbol. For 55 symbols across 4 timeframes, that's 220 sequential API calls — even though every single one is independent and could happen simultaneously.
On top of that, different parts of the pipeline were fetching the same data independently. The prediction service would fetch 1-hour candles for BTC/USDT. Then the multi-timeframe analyser would fetch 1-hour candles for BTC/USDT again. Two separate round trips for the same data.
We redesigned the data layer to prefetch everything in one coordinated burst. All 55 symbols, all 4 timeframes, fired concurrently with intelligent batching that respects exchange rate limits. The results come back as a unified data cache — every downstream system pulls from this cache instead of making its own API calls. Zero duplicate fetches.
This required changing how data flows through the system. Previously, each analysis function was self-contained: it accepted a symbol name, fetched its own data, and returned a result. Clean API, but every function independently decided when and how to fetch data. The new design separates data acquisition from data processing — less elegant, but the performance difference is dramatic.
Data-layer redesign cut total endpoint time from 25 seconds to about 11 seconds. Meaningful, but the computational bottleneck was still untouched.
How Does Python Handle CPU-Bound ML Workloads?
Python handles CPU-bound ML workloads through GIL release — when libraries like NumPy and pandas execute their C-level computation, they release Python's Global Interpreter Lock, allowing genuine multi-core parallelism through threading. This means a Python ML pipeline can achieve near-native performance for numerical work without switching to C++ or Rust.
This subtlety is widely misunderstood. Python's GIL is a real limitation for pure Python CPU work. But our indicator calculations don't run in Python. They run in C, via NumPy, pandas, and the pandas_ta library. When pandas computes a rolling standard deviation, the GIL is released for the duration of that C-level computation.
We restructured the prediction pipeline to offload all CPU-heavy indicator work to a managed thread pool using asyncio.to_thread(). The async orchestration layer fires off 30 symbol analyses concurrently. Each one runs in the thread pool, computes its indicators in C (releasing the GIL), and returns the results.
Getting this right required solving several challenges:
Thread safety. The original code had shared mutable state in places we didn't expect. Singleton instances caching intermediate results. Class-level attributes being modified during computation. All of this had to be audited and either eliminated or made thread-safe. In a serial pipeline, shared state is convenient. In a concurrent pipeline, it's a race condition.
Error isolation. When 30 analyses run concurrently and 3 of them fail, the failures can't poison the 27 successful results. We implemented return_exceptions=True where exceptions are collected alongside results, failed symbols are logged and skipped, and users still get picks from the symbols that succeeded.
Thread pool tuning. On our 2-core VPS, the default pool gives us 6 worker threads. We tested various pool sizes and found the default reasonable, but the profiling revealed that later symbols showed inflated wall-clock times due to thread pool queuing — understanding this was essential for interpreting our timing data correctly.
Threading brought total endpoint time from 11 seconds down to about 7.5 seconds. Better, but still not where we needed to be.
Phase 4: The Unified Computation Engine
This was the big one. The single change that delivered the most dramatic improvement.
Remember: feature extraction (47% of per-symbol time) and regime detection (51%) were each independently computing the same expensive indicators. Same RSI. Same ATR. Same Bollinger Bands. Same EMA20 and EMA50. Same ADX. Computed twice, from the same raw data, producing the same numbers, in two separate code paths.
The naive fix would be a per-symbol indicator cache. But that adds complexity in all the wrong places — cache invalidation, memory management, thread-safe access. All for something that should be structurally impossible.
Our approach was more fundamental: redesign the feature extraction system to produce everything downstream systems need in a single computational pass. One set of indicator calculations serving both the ML feature pipeline and the regime detection system.
The two systems expected data in completely different formats. The ML feature system needs normalised time-series features — full DataFrame columns spanning the lookback window. The regime detection system needs point-in-time scalar values — "what is ADX right now?" Same underlying indicators, completely different representations.
We built a unified computation layer that computes each indicator once and produces both representations simultaneously. 8 pandas_ta calls instead of the previous 21+. From those 8 calls, it constructs both a features DataFrame for the ML model and a regime metrics dictionary for the classifier.
The regime detector was modified to accept pre-computed metrics as an optional parameter. When metrics are provided, it skips its entire _calculate_metrics() method and jumps straight to classification logic — pure conditional checks that take microseconds.
The result: regime detection went from ~1.4 seconds per symbol to effectively zero. Not "fast" — zero. The computation simply doesn't happen, because feature extraction already did the work and passed the results forward.
Phase 5: Intelligent Feature Pruning
Our 13,500-model-fit research had already told us exactly which features matter. Out of the 60+ features our original extraction pipeline computed, only 15 had meaningful predictive power for crypto, and just 6 for equities. The other 45+ were computed, assembled into a DataFrame, then immediately discarded by the feature selection step.
We were computing Stochastic RSI, Keltner Channels, Williams %R, OBV slope, volume trend, wick ratios, inside bars, outside bars, doji patterns, engulfing patterns, hour-of-day encoding — all of it mathematically intensive, all of it thrown away before the model ever sees it.
The original design made sense when we built it. We didn't know which features would matter. We computed everything, tested everything, and let the research tell us what worked. That's good science. But once the research was done and the winners were identified, continuing to compute the losers on every request was pure waste.
We rebuilt the extraction pipeline to compute only what the model actually uses. For crypto, that's 6 unique pandas_ta calls to produce the 15 model features (plus 2 more for regime metrics — 8 total). 8 pandas_ta calls instead of 15+, nearly halving per-symbol feature extraction time.
Phase 6: Pipeline Reordering and Macro Feature Elimination
Two smaller but meaningful optimisations completed the picture.
Operation reordering. The original pipeline ran every stage in a fixed order. We restructured to put regime detection first — since it now uses pre-computed metrics and completes in microseconds, there's no cost. The regime information is then available to downstream stages for smarter scheduling.
Macro feature elimination. Profiling revealed we were computing macro-economic features (FRED data, market-wide indicators) and injecting them into the feature DataFrame — only for feature selection to immediately discard them. None of the macro features made it into the top 15. We removed the macro feature computation from the prediction path entirely, and the training pipeline no longer computes them either, so neither path wastes time on features that don't contribute.
The Results
After all six phases:
| Metric | Before | After | Improvement | |--------|--------|-------|-------------| | Daily Picks (30 crypto) | 25s | ~2s | 12x faster | | Morning Briefing | 25s | ~2s | 12x faster | | Market Analysis | 18s | ~1.5s | 12x faster | | Per-symbol prediction | 2.8s | <0.1s | 28x faster | | Cached responses | 0.3s | 0.3s | (already fast) |
That's not a typo. Per-symbol prediction went from 2.8 seconds to under 100 milliseconds — a 28x improvement. The endpoint-level gains are somewhat less dramatic because network I/O for fetching live market data still takes real time, but the computational work that we control is now a tiny fraction of overall request time.
Where the time goes now
| Stage | Before | After | |-------|--------|-------| | Feature extraction | 1.3s | ~0.4s | | Regime detection | 1.4s | ~0s | | Model inference | 0.002s | 0.002s | | Everything else | 0.06s | 0.06s | | Total per symbol | 2.8s | ~0.5s |
What Shortcuts Did We Refuse to Take?
We refused to reduce symbol coverage (55+ assets stay), cut analysis depth (full multi-timeframe pipeline stays), rely on caching as a primary strategy (first-load users deserve fast responses too), upgrade hardware (same modest VPS), or approximate indicator values (accuracy depends on exact computation over specific windows).
Throughout this process, we had plenty of opportunities to take shortcuts. We rejected all of them.
We didn't reduce the number of symbols. Analysing 20 instead of 55 would have been faster, but it would have given users a worse product. The best trade of the day might be in a mid-cap altcoin that a restricted scan would have excluded.
We didn't cut analysis depth. Every symbol still gets multi-timeframe analysis across four timeframes, regime detection with six classifications, ML prediction with confidence scoring, meta-labeling, alignment scoring, and natural-language explanations.
We didn't add caching as a primary strategy. Caching was already in place before these optimisations. The first user to hit an expired cache should get a fast response too.
We didn't switch to a bigger server. Same modest VPS. The improvements came entirely from doing less redundant work. Hardware scaling has diminishing returns and ongoing costs, but algorithmic improvements are permanent. This echoes something I've seen across 200+ data extraction projects on Apify — the first version always fetches too much and processes too much. The refinement is always about doing less, not doing it faster.
We didn't sacrifice accuracy. Our research showed that accuracy depends on specific features computed over specific windows. Computing them incorrectly defeats the purpose.
Lessons Learned
Profile before you optimise. Always. Our intuitions about where the time was going were completely wrong. We assumed network I/O and model inference. The actual bottleneck was duplicated numerical computation. Without microsecond-level profiling, we would have spent weeks optimising the wrong systems.
Architectural boundaries hide redundancy. Clean separation of concerns is generally good engineering. But when separate modules independently compute the same expensive operations on the same data, the boundaries themselves become a performance problem. Sometimes you need to break clean abstractions to eliminate waste. The unified computation engine is architecturally messier than two independent modules. But it's 28x faster.
Python can be fast enough. There's a persistent belief that Python is too slow for real-time computation. This is wrong when you understand where Python's actual computation happens. Our indicator calculations run in C, via NumPy and pandas. Python is the orchestration layer. With proper threading (exploiting GIL release during C-level computation), we get genuine multi-core parallelism from a Python codebase.
The best optimisation is doing less work. We didn't make any single computation faster. We didn't find a faster algorithm for RSI. We just stopped computing things we didn't need (45+ unused features), and stopped computing things we did need more than once (6 duplicated indicators). The fastest code is the code that doesn't run.
Research pays compound interest. The 13,500-model-fit experiment had an unexpected second payoff. It wasn't just about finding which features predict prices — it also told us which features don't. That negative knowledge turned out to be just as valuable for performance as the positive knowledge was for accuracy.
The daily picks load in 2 seconds now. The morning briefing is ready when you are. And you don't have to wonder if the page crashed. That's what good engineering should feel like — you shouldn't notice it at all.
See the faster pipeline in action with the Daily Picks widget, or start paper trading to get ML-powered AI signals on 55+ assets.
Last updated: March 2026
Last updated: 21 November 2026