Custom Out-of-Sample Testing System for Crypto Trading Strategies

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Custom Out-of-Sample Testing System for Crypto Trading Strategies
Medium
~3-5 days
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1359
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

You wrote a trading strategy: on Ethereum historical data it shows a Sharpe of 2.8, max drawdown 12%, win rate 65%. You launch it on a demo account — a week later you're down 40%. The reason: overfitting to history. Out-of-sample (OOS) testing is the only way to filter out such strategies before you risk real capital. We build custom OOS testing systems that integrate into your algorithmic pipeline.

Our experience in this area: 5+ years developing trading systems for cryptocurrencies, over 60 completed projects, including DeFi frameworks for arbitrage and market making. We guarantee correct implementation: all checks are tested on synthetic data with known answers. We provide full code, documentation, and consultations.

What is out-of-sample testing and why is it needed?

Out-of-sample (OOS) testing is the evaluation of a trading strategy on data that was not used during its creation. It filters out overfitted algorithms before they hit a real account. Without OOS, you risk capital based on random coincidences in historical data.

What problems does OOS testing solve?

Overfitting. If a strategy works only on the data it was tuned on, it's useless. An OOS test reveals true generalization ability. We use statistical tests (t-test, effective sample size corrected for autocorrelation) to assess significance of OOS results. In our practice, 70% of strategies that pass IS optimization fail OOS validation.

Look-ahead bias and data leakage. A common mistake: when splitting into IS/OOS, indicators that use future data are not shifted. We automatically verify that the OOS period is fully isolated: the last 20% of chronology. The split code is always strict, with date checks.

Statistical insignificance. A small sample or high autocorrelation makes results random. Our framework calculates p-value for OOS returns and adjusts the number of effective observations. Only if p < 0.05 and Sharpe > 0.5 is the strategy allowed for deployment.

How we do it

Tech stack: Python 3.10+, pandas, scipy, numpy. We use unit testing for validation components. The client receives not only a report but also an interactive dashboard with metrics: Sharpe degradation, drawdowns, win rate.

Example from a recent case: for a DeFi arbitrage bot on Polygon, we implemented OOS validation with walk-forward optimization. On OOS data, Sharpe dropped from 3.2 to 1.8, but remained statistically significant (p=0.01). The client declined deployment, saving about $12k in fees and liquidity. Such a check is worth the investment.

Validation framework

import pandas as pd

def create_oos_split(data: pd.DataFrame, oos_pct: float = 0.20) -> tuple:
    """
    Create strict IS/OOS split.
    OOS is the last 20% of data chronologically.
    """
    split_idx = int(len(data) * (1 - oos_pct))
    
    in_sample = data.iloc[:split_idx]
    out_of_sample = data.iloc[split_idx:]
    
    print(f"In-sample: {in_sample.index[0].date()} → {in_sample.index[-1].date()} ({len(in_sample)} bars)")
    print(f"Out-of-sample: {out_of_sample.index[0].date()} → {out_of_sample.index[-1].date()} ({len(out_of_sample)} bars)")
    
    return in_sample, out_of_sample
class OOSValidator:
    def __init__(self, backtester, significance_threshold: float = 0.05):
        self.backtester = backtester
        self.alpha = significance_threshold

    def validate(
        self,
        strategy_params: dict,
        is_result: BacktestResult,
        oos_data: pd.DataFrame,
    ) -> OOSValidationReport:
        # Run final test on OOS data
        oos_result = self.backtester.run(strategy_params, oos_data)

        # Statistical significance of OOS results
        oos_returns = oos_result.equity_curve.pct_change().dropna()
        significance = self._test_significance(oos_returns)

        # Compare IS vs OOS
        is_vs_oos = self._compare_is_oos(is_result, oos_result)

        # Verdict
        passed = self._evaluate_verdict(oos_result, significance, is_vs_oos)

        return OOSValidationReport(
            is_result=is_result,
            oos_result=oos_result,
            significance=significance,
            is_vs_oos_comparison=is_vs_oos,
            passed=passed,
            recommendation=self._get_recommendation(passed, is_vs_oos),
        )

    def _test_significance(self, returns: pd.Series) -> dict:
        """Test statistical significance of positive returns"""
        from scipy import stats

        # t-test: H0: mean return == 0
        t_stat, p_value = stats.ttest_1samp(returns, 0)

        # Number of independent observations accounting for autocorrelation
        n_effective = self._effective_sample_size(returns)

        return {
            't_statistic': t_stat,
            'p_value': p_value,
            'is_significant': p_value < self.alpha and t_stat > 0,
            'n_effective': n_effective,
        }

    def _effective_sample_size(self, returns: pd.Series) -> float:
        """Adjust sample size for autocorrelation"""
        n = len(returns)
        autocorr = returns.autocorr(1)
        if abs(autocorr) >= 1:
            return n
        return n * (1 - autocorr) / (1 + autocorr)

    def _compare_is_oos(self, is_result: BacktestResult, oos_result: BacktestResult) -> dict:
        is_m = is_result.metrics
        oos_m = oos_result.metrics

        return {
            'sharpe_ratio_degradation': (is_m.sharpe_ratio - oos_m.sharpe_ratio) / max(abs(is_m.sharpe_ratio), 0.01),
            'return_ratio': oos_m.annual_return_pct / max(is_m.annual_return_pct, 0.01),
            'drawdown_ratio': oos_m.max_drawdown_pct / max(abs(is_m.max_drawdown_pct), 0.01),
            'win_rate_change': oos_m.win_rate - is_m.win_rate,
        }

    def _evaluate_verdict(self, oos_result, significance, comparison) -> bool:
        # Criteria for passing OOS test
        checks = [
            oos_result.metrics.sharpe_ratio > 0.5,         # positive Sharpe
            significance['is_significant'],                   # statistically significant
            comparison['sharpe_ratio_degradation'] < 0.7,    # degradation < 70%
            oos_result.metrics.max_drawdown_pct > -40,       # drawdown < 40%
            oos_result.metrics.total_trades >= 15,           # enough trades
        ]
        return all(checks)


# Function to print report
def print_oos_report(report: OOSValidationReport):
    print("=" * 60)
    print("OOS VALIDATION REPORT")
    print("=" * 60)

    print(f"\n{'IS':25} {'OOS':>10}")
    print("-" * 40)
    print(f"{'Sharpe Ratio':25} {report.is_result.metrics.sharpe_ratio:>10.2f} {report.oos_result.metrics.sharpe_ratio:>10.2f}")
    print(f"{'Annual Return %':25} {report.is_result.metrics.annual_return_pct:>10.1f} {report.oos_result.metrics.annual_return_pct:>10.1f}")
    print(f"{'Max Drawdown %':25} {report.is_result.metrics.max_drawdown_pct:>10.1f} {report.oos_result.metrics.max_drawdown_pct:>10.1f}")
    print(f"{'Win Rate %':25} {report.is_result.metrics.win_rate*100:>10.1f} {report.oos_result.metrics.win_rate*100:>10.1f}")

    comp = report.is_vs_oos_comparison
    print(f"\nSharpe degradation: {comp['sharpe_ratio_degradation']:.1%}")
    print(f"OOS/IS return ratio: {comp['return_ratio']:.2f}x")

    sig = report.significance
    print(f"\nStatistical significance: p={sig['p_value']:.4f} (significant: {sig['is_significant']})")
    print(f"Effective sample size: {sig['n_effective']:.0f}")

    verdict = "PASSED" if report.passed else "FAILED"
    print(f"\n{'='*20} {verdict} {'='*20}")
    print(f"Recommendation: {report.recommendation}")

How to determine the correct data split?

One key question is what percentage of data to allocate to OOS. Standard: 70/20/10 (IS/OOS/validation) or 80/20 for simple cases. For walk-forward optimization we use a rolling window: 12 months IS, 3 months OOS. Cryptocurrencies require more frequent recalibration — once a month.

Metric In-Sample Out-of-Sample Acceptable Deviation
Sharpe Ratio 2.0 – 3.0 > 0.5 Degradation < 70%
Annual Return 30% – 60% > 0% Reduction by 2–3x
Max Drawdown < 20% < 40% Increase up to 2x
Win Rate 55% – 70% > 50% Decrease up to 10%

How to evaluate statistical significance of OOS results?

For significance evaluation we use the t-test and sample size adjustment for autocorrelation. If p-value < 0.05 and Sharpe > 0.5, the strategy is considered to have passed OOS validation. More about the t-test can be read on Wikipedia.

Process of work

Stage What we do Result
Analytics Gather requirements: asset types, trade frequency, time frames Technical specification
Design Develop architecture: data split, validation classes, integration with backtester Architecture documentation
Implementation Write prototype in Python considering your stack Repository with code
Testing Validate on synthetic data, test for known bugs (look-ahead bias, data snooping) Validation report
Deployment Integrate into CI/CD pipeline, train the team Access to system + documentation

Why are OOS results always worse than IS?

This is expected: the strategy is fitted to IS, so degradation on new data is inevitable. What matters is not the absolute difference but its reasonableness: Sharpe degradation no more than 70%, OOS returns positive. If OOS is better than IS, it's a symptom of look-ahead bias and needs rechecking.

Typical mistakes in OOS testing

  • Looking at OOS before finalizing the strategy. One glance is enough to make the data no longer out-of-sample.
  • Using random split instead of chronological. Trading is a time series; random shuffling destroys temporal structure.
  • Not checking statistical significance. With few trades (less than 15), any result is random.
  • Ignoring autocorrelation. Daily returns are correlated; effective sample size is smaller.

Due to look-ahead bias, one of our clients lost over $20k on a real account. Preventing such losses is the purpose of OOS testing.

What's included in the work (deliverables)

  • OOS validation framework with source code and tests
  • Integration with your backtester (Python libraries)
  • Report explaining metrics and recommendations
  • Documentation on usage and customization
  • Access to repository with change history
  • Consultation support for 30 days

Order the implementation of OOS testing — contact us for a consultation. We will evaluate your strategy and propose an optimal solution. Get a consultation without obligations. Alternatively, if you want to test an existing strategy, our team can perform an audit in 1-2 days.

Why exchange development requires deep domain expertise

We develop exchanges — not 'chart sites,' but matching engines that process thousands of orders per second without delay, route liquidity between pools, and guarantee that no user gains access to others' funds. Teams that start with the UI and postpone the engine 'for later' end up rewriting everything in six months in 90% of cases.

Order Book vs AMM: where most projects break

Centralized exchanges (CEX) are built around an order book + matching engine. Decentralized exchanges (DEX) either also use an order book (dYdX on StarkEx, Serum/OpenBook on Solana) or an AMM with concentrated liquidity (Uniswap v3/v4, Curve, Balancer). A classic mistake when developing a CEX is implementing the matching engine on top of a relational database with transactions for each match. PostgreSQL handles ~500 RPS without special effort, but at peak loads of 5,000–10,000 orders per second, it turns into a deadlock nightmare. The correct architecture: in-memory order book (Redis Sorted Sets or custom C++/Rust structure), asynchronous writing of matches to PostgreSQL via a queue (Kafka/RabbitMQ), and a separate settlement service that finally updates balances.

For DEX, the most painful problem is sandwich attacks and MEV. A pool with a plain xy=k AMM without slippage protection becomes a target for MEV bots within hours of launch. Uniswap v2 lost hundreds of millions of dollars in user liquidity. Solutions: integration with Flashbots Protect, a commit-reveal scheme for orders, or switching to TWAMM (Time-Weighted AMM) for large trades.

Concentrated liquidity and impermanent loss

Uniswap v3 introduced concentrated liquidity – LPs choose a price range in which to provide liquidity. Capital efficiency increased 4,000x compared to v2 for stable pairs. But implementing this mechanism correctly is non-trivial. The Uniswap v3 liquidity contract uses tick-based accounting: the price space is divided into discrete ticks (tick = log₁.0001(price)), each tick stores accumulated fee growth and liquidity delta. When creating a position, the lower and upper ticks are computed, and the contract recalculates all active positions at each swap. Storage layout is critical here – incorrect variable packing in slots easily adds 40–60% to swap gas cost.

We implemented a Uniswap v3 fork for a client on Polygon with a custom fee tier system. The initial version consumed 180k gas for a swap across 2 ticks. After slot packing of variables in Tick.Info and inlining several internal calls, it dropped to 112k gas. This reduced gas costs by 38% and saved the client substantial costs on fees monthly. The techniques applied are described in the Uniswap v3 Whitepaper and confirmed by our audit experience.

How a matching engine delivers performance

A production-ready matching engine is built according to the following scheme:

  • Order ingestion layer – WebSocket gateway (Go or Rust), accepts orders, validates signature, checks balance via Redis, queues them. Latency at this level must be <1ms.
  • Matching core – single-threaded event loop (eliminates race conditions without mutexes). In memory, we hold two Sorted Sets for each trading instrument: bids and asks. FIFO matching for limit orders, immediate-or-cancel for market orders. Throughput with a proper Rust implementation – 500k–1M matches per second on a single core.
  • Settlement service – reads matches from Kafka, atomically updates balances in PostgreSQL (UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1). Optimistic locking via row versioning.
  • Withdrawal pipeline – separate service with cold/hot wallet architecture. The hot wallet holds 5–10% of total deposits, the rest is cold storage with multi-sig (Gnosis Safe or custom HSM). Automatic withdrawals only from hot wallet, large amounts require manual authorization.
Component Technology Latency / Throughput
Order gateway Go + WebSocket <1ms p99
Matching engine Rust (in-memory) 500k+ orders/sec
Balance store Redis (write-through) <0.5ms
Settlement DB PostgreSQL 14+ ~50k TPS with partitioning
Event streaming Apache Kafka 1M+ events/sec
Blockchain node Geth / Solana validator depends on chain

How our exchange development process ensures reliability

Smart contracts and gas optimization

For EVM-based DEX (Ethereum, Arbitrum, Optimism, Polygon), the entire critical path lives in Solidity. Main contracts: Pool, Factory, Router, PositionManager (for v3-like), and Quoter for off-chain calculations. Typical mistakes we see in audits:

Reentrancy via callback. Uniswap v3 uses flash swap with a callback (uniswapV3SwapCallback). If your router lacks a nonReentrant guard and you don't check msg.sender == pool, the contract gets drained via a nested call. This is not hypothetical – several v3 forks lost funds this way.

Oracle manipulation in AMM. If your contract uses the spot price from the pool for collateral calculation, it is front-runnable. Correct: TWAP over 30+ minutes (Uniswap v3 OracleLib) or an external oracle (Chainlink).

Unbounded loops in liquidity range. If a swap crosses many ticks in a row (price impact 80%+), gas may exceed the block limit. Need MAX_TICKS_CROSSED with partial fill and returning the remainder.

For Solana DEX (Anchor framework, Rust), the architecture is fundamentally different: account-based model, Program Derived Addresses (PDA) instead of storage, Cross-Program Invocations instead of internal calls. Solana's throughput (~3,000–4,000 TPS vs 15–30 on Ethereum mainnet) allows building on-chain order books – exactly what Phoenix DEX does.

Liquidity bootstrapping and aggregator integration

Launching a pool is not enough – you need to ensure liquidity at launch. Practical mechanisms:

  • Liquidity Bootstrapping Pool (LBP) – initial price is high, asset weights dynamically shift, creating selling pressure and even token distribution. Implemented in Balancer v2.
  • Initial Liquidity Offering via Uniswap v3 – adding liquidity in a narrow range around the initial price, then gradually expanding as volume grows. Requires active liquidity management or integration with Arrakis/Gamma.
  • Integration with 1inch, Paraswap, Li.Fi – aggregators bring traffic but require standard compliance: the pool must have correct getAmountsOut, support ERC-20 approval/permit, and not have custom transfer hooks that break the aggregator's routing.

Development process and deliverables

Analytics and design begin with choosing the architectural model: CEX with custodial storage, non-custodial DEX, or hybrid (off-chain order book + on-chain settlement, like dYdX v3). This decision determines everything – regulatory load, tech stack, team.

Development proceeds in layers: first smart contracts with full Foundry coverage (fuzzing, invariant testing), then backend services, then integration layer, and finally frontend. Testing includes fork testing on mainnet via Foundry – we reproduce real liquidity conditions, not synthetic ones.

Audit is mandatory before mainnet deployment. For DEX contracts, minimally one firm with manual review (Trail of Bits, Spearbit, Code4rena contest). For CEX custody, audit of key storage processes. We guarantee all contracts undergo formal verification and fuzzing testing (Echidna, Foundry invariant).

Estimated timelines

Exchange type Timeframe
DEX (AMM, xy=k) 3 to 5 months
DEX with concentrated liquidity (v3-like) 6 to 10 months
CEX (matching engine + custody + trading UI) 8 to 14 months
Integration with existing protocol 4 to 8 weeks

Cost is calculated individually after a technical briefing: chain selection, throughput requirements, custodial model. Our certified engineers with 10+ years of experience will help you choose the optimal architecture and avoid common pitfalls. Contact our team for a detailed proposal.

Pitfalls to avoid at launch

  • Forgetting the price oracle in AMM. Spot price can be manipulated with a flash loan in one transaction. If your lending protocol uses the spot price from its own pool, that's a bug.
  • Hot wallet without limits. A CEX without daily limits on automatic withdrawals is an invitation for attackers. Compromising one key should lose at most 10% of total funds.
  • Absence of circuit breaker. A 40% price drop in 5 minutes should halt automatic liquidations or withdrawals until manual review. Without this, a cascading liquidation spiral destroys all TVL.
  • Incorrect decimal handling. USDC uses 6 decimals, WBTC – 8, most tokens – 18. Mixing without normalization leads to either precision loss or overflow. Solidity has no float; we work with fixed-point using FullMath (mulDiv with overflow protection).

Want to avoid these problems? Get a consultation — we will select the architecture for your project and provide exact timelines. Order exchange development with quality guarantee and ongoing support.