JSPM

@neural-trader/backtesting

1.0.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 47
  • Score
    100M100P100Q99075F
  • License MIT OR Apache-2.0

High-performance backtesting engine for Neural Trader - Rust-powered NAPI bindings

Package Exports

  • @neural-trader/backtesting
  • @neural-trader/backtesting/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@neural-trader/backtesting) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

@neural-trader/backtesting

High-performance backtesting engine for Neural Trader with Rust-powered NAPI bindings.

Overview

Test your trading strategies against historical data with near-native performance. This package wraps the nt-backtesting Rust crate with zero-overhead Node.js bindings.

Installation

npm install @neural-trader/backtesting @neural-trader/core

Features

  • Ultra-fast execution - Rust performance with JavaScript ease
  • 📊 Comprehensive metrics - Sharpe, Sortino, max drawdown, win rate, and more
  • 💰 Realistic simulation - Commission, slippage, and mark-to-market accounting
  • 📈 Equity curves - Full trade history and equity tracking
  • 🔄 Signal-based - Works with any strategy that generates signals

Quick Start

import { BacktestEngine } from '@neural-trader/backtesting';
import type { BacktestConfig, Signal } from '@neural-trader/core';

// Configure backtest
const config: BacktestConfig = {
  initialCapital: 100000,
  startDate: '2024-01-01',
  endDate: '2024-12-31',
  commission: 0.001,        // 0.1% per trade
  slippage: 0.0005,         // 0.05% slippage
  useMarkToMarket: true
};

// Create engine
const engine = new BacktestEngine(config);

// Generate signals (from your strategy)
const signals: Signal[] = [
  {
    id: '1',
    strategyId: 'momentum-1',
    symbol: 'AAPL',
    direction: 'long',
    confidence: 0.85,
    entryPrice: 150.00,
    stopLoss: 145.00,
    takeProfit: 160.00,
    reasoning: 'Strong momentum breakout',
    timestampNs: Date.now() * 1_000_000
  }
  // ... more signals
];

// Run backtest
const result = await engine.run(signals, 'path/to/market-data.csv');

// Analyze results
console.log('Performance Metrics:');
console.log(`Total Return: ${(result.metrics.totalReturn * 100).toFixed(2)}%`);
console.log(`Sharpe Ratio: ${result.metrics.sharpeRatio.toFixed(2)}`);
console.log(`Max Drawdown: ${(result.metrics.maxDrawdown * 100).toFixed(2)}%`);
console.log(`Win Rate: ${(result.metrics.winRate * 100).toFixed(1)}%`);
console.log(`Profit Factor: ${result.metrics.profitFactor.toFixed(2)}`);
console.log(`Total Trades: ${result.metrics.totalTrades}`);

// Export trades to CSV
const csv = engine.exportTradesCsv(result.trades);

API Reference

BacktestEngine

class BacktestEngine {
  constructor(config: BacktestConfig);

  // Run backtest with strategy signals and market data
  run(signals: Signal[], marketDataPath: string): Promise<BacktestResult>;

  // Calculate performance metrics from equity curve
  calculateMetrics(equityCurve: number[]): BacktestMetrics;

  // Export trades to CSV format
  exportTradesCsv(trades: Trade[]): string;
}

BacktestResult

interface BacktestResult {
  metrics: BacktestMetrics;  // Performance statistics
  trades: Trade[];           // All executed trades
  equityCurve: number[];     // Portfolio value over time
  dates: string[];           // Corresponding timestamps
}

BacktestMetrics

interface BacktestMetrics {
  totalReturn: number;       // Total return as decimal (0.15 = 15%)
  annualReturn: number;      // Annualized return
  sharpeRatio: number;       // Risk-adjusted return
  sortinoRatio: number;      // Downside risk-adjusted return
  maxDrawdown: number;       // Maximum drawdown
  winRate: number;           // Winning trades / total trades
  profitFactor: number;      // Gross profit / gross loss
  totalTrades: number;       // Number of trades
  winningTrades: number;     // Number of winning trades
  losingTrades: number;      // Number of losing trades
  avgWin: number;            // Average winning trade
  avgLoss: number;           // Average losing trade
  largestWin: number;        // Largest winning trade
  largestLoss: number;       // Largest losing trade
  finalEquity: number;       // Final portfolio value
}

Performance

  • Execution Speed: Process 10,000+ trades in milliseconds
  • Latency: <2ms overhead for NAPI calls
  • Memory: Efficient Rust memory management

Package Size

~300 KB (compressed native binary)

Platform Support

  • ✅ Linux x64 (GNU)
  • ✅ Linux x64 (musl)
  • ✅ macOS x64 (Intel)
  • ✅ macOS ARM64 (Apple Silicon)
  • ✅ Windows x64 (MSVC)
  • @neural-trader/core - Core types (required)
  • @neural-trader/strategies - Trading strategies
  • @neural-trader/risk - Risk management
  • neural-trader - Complete platform

License

MIT OR Apache-2.0