@neural-trader/predictor

Conformal prediction SDK for neural trading with mathematically guaranteed prediction intervals
Part of the Neural Trader ecosystem - AI-powered algorithmic trading platform
Built by rUv | GitHub
A production-ready TypeScript/JavaScript library providing distribution-free prediction intervals with rigorous mathematical guarantees. Available in three high-performance implementations (Pure JS, WebAssembly, Native Node.js bindings) to fit any deployment environment - from browsers to high-frequency trading servers.
🌟 Why Conformal Prediction?
Traditional machine learning gives you point estimates that are often wrong. Conformal prediction gives you guaranteed intervals:
Traditional ML: "Bitcoin will be $50,000" (70% chance you're wrong)
Conformal ML: "Bitcoin will be between $48,500-$51,500" (90% mathematical guarantee)
This makes conformal prediction essential for:
- Risk Management: Know your worst-case scenarios with probability guarantees
- Automated Trading: Set stop-losses and take-profits with statistical confidence
- Regulatory Compliance: Provable uncertainty quantification for audits
- Portfolio Optimization: Reliable confidence bounds for position sizing
Core Principle
Conformal prediction provides a mathematical guarantee:
P(y ∈ [lower, upper]) ≥ 1 - α
Get guaranteed intervals instead of uncertain point estimates. Perfect for trading, risk management, and any application requiring reliable uncertainty quantification.
🎯 Key Features
- Multiple Implementations:
- Pure JavaScript (portable, works everywhere)
- WebAssembly (5-10x faster, zero dependencies)
- Native Node.js bindings (near-Rust performance)
- Auto-detection with fallback support
- Split Conformal Prediction: Distribution-free intervals with
(1-α) coverage guarantee
- Adaptive Conformal Inference (ACI): PID-controlled dynamic coverage adjustment
- Conformalized Quantile Regression (CQR): Quantile-based intervals with guarantees
- Multiple Nonconformity Scores: Absolute, normalized, and quantile-based
- Real-time Streaming: Efficient incremental updates
- Trading Integration: Seamless integration with
@neural-trader/neural
- Browser & Node.js: Works in browsers, Node.js, Electron, React Native
- TypeScript Support: Full type definitions, 100% type-safe
💼 Real-World Use Cases
1. Algorithmic Trading
const interval = predictor.predict(nextPrice);
executeTrade({
entry: interval.point,
stopLoss: interval.lower,
takeProfit: interval.upper,
});
2. Portfolio Risk Management
const returns = calculatePortfolioReturns(positions);
const interval = predictor.predict(expectedReturn);
const VaR95 = interval.lower;
const maxLoss = portfolio.value * VaR95;
3. Options Pricing & Greeks
const optionInterval = predictor.predict(blackScholesPrice);
const conservativeBid = optionInterval.lower;
const conservativeAsk = optionInterval.upper;
4. High-Frequency Trading
const predictor = new WasmConformalPredictor({ alpha: 0.05 });
for (const tick of marketTicks) {
const interval = predictor.predict(tick.midPrice);
if (interval.width() < SPREAD_THRESHOLD) {
placeMarketMakerOrder(interval.lower, interval.upper);
}
}
5. Compliance & Reporting
const report = {
prediction: interval.point,
lowerBound: interval.lower,
upperBound: interval.upper,
coverage: "95%",
method: "Split Conformal Prediction",
regulatoryCompliant: true,
};
📊 Performance Comparison
| Rust (native) | <50μs | <20ms | <5MB | - | ✓ |
| WASM | <500μs | <150ms | <15MB | ✓ | ✓ |
| Pure JS | <2ms | <500ms | <25MB | ✓ | ✓ |
Real-world targets:
- Prediction latency: <1ms (guaranteed interval)
- Calibration time: <100ms for 2,000 samples
- Throughput: 10,000+ predictions/second
- Memory footprint: <10MB for typical usage
🚀 Quick Start
Installation
npm install @neural-trader/predictor
yarn add @neural-trader/predictor
pnpm add @neural-trader/predictor
Pure JavaScript (Works Everywhere)
import { ConformalPredictor, AbsoluteScore } from '@neural-trader/predictor';
const predictor = new ConformalPredictor({
alpha: 0.1,
scoreFunction: new AbsoluteScore(),
});
await predictor.calibrate(
[100.0, 105.0, 98.0, 102.0],
[102.0, 104.0, 99.0, 101.0]
);
const interval = predictor.predict(103.0);
console.log(`Prediction: ${interval.point}`);
console.log(`90% Confidence: [${interval.lower}, ${interval.upper}]`);
console.log(`Interval width: ${interval.width()}`);
console.log(`Coverage: ${interval.coverage() * 100}%`);
WebAssembly (5-10x Faster)
import { initWasm, WasmConformalPredictor } from '@neural-trader/predictor/wasm';
await initWasm();
const predictor = new WasmConformalPredictor({
alpha: 0.1,
scoreFunction: 'absolute',
});
await predictor.calibrate(predictions, actuals);
const interval = predictor.predict(103.0);
Native Node.js Bindings (Maximum Speed)
import { NativeConformalPredictor } from '@neural-trader/predictor/native';
const predictor = new NativeConformalPredictor({
alpha: 0.1,
scoreFunction: 'absolute',
});
await predictor.calibrate(predictions, actuals);
const interval = predictor.predict(103.0);
Auto-Select Best Implementation
import { createPredictor } from '@neural-trader/predictor';
const predictor = await createPredictor({
alpha: 0.1,
preferNative: true,
fallbackToWasm: true,
});
console.log(`Using: ${predictor.implementation}`);
📚 Adaptive Trading Example
import { AdaptiveConformalPredictor } from '@neural-trader/predictor';
const predictor = new AdaptiveConformalPredictor({
targetCoverage: 0.90,
gamma: 0.02,
scoreFunction: new AbsoluteScore(),
});
for await (const { prediction, actual } of marketDataStream) {
const interval = await predictor.predictAndAdapt(prediction, actual);
if (interval.width() < MAX_INTERVAL_WIDTH && interval.point > THRESHOLD) {
console.log(`TRADE: Buy at ${interval.point}`);
console.log(`Risk: Short at ${interval.lower}`);
console.log(`Target: Long at ${interval.upper}`);
await executeTrade({
type: 'BUY',
quantity: positionSize,
stopLoss: interval.lower,
takeProfit: interval.upper,
});
}
const metrics = await predictor.getMetrics();
console.log(`Coverage: ${metrics.empiricalCoverage * 100}%`);
console.log(`Current alpha: ${metrics.currentAlpha}`);
}
🌐 Browser Usage
<!DOCTYPE html>
<html>
<head>
<script type="module">
import { ConformalPredictor, AbsoluteScore } from 'https://cdn.jsdelivr.net/npm/@neural-trader/predictor@latest/dist/index.mjs';
const predictor = new ConformalPredictor({
alpha: 0.1,
scoreFunction: new AbsoluteScore(),
});
document.getElementById('predict-btn').addEventListener('click', async () => {
await predictor.calibrate([100, 105, 98, 102], [102, 104, 99, 101]);
const interval = predictor.predict(103);
document.getElementById('result').textContent = `[${interval.lower}, ${interval.upper}]`;
});
</script>
</head>
<body>
<button id="predict-btn">Make Prediction</button>
<div id="result"></div>
</body>
</html>
📖 API Reference
ConformalPredictor
class ConformalPredictor {
constructor(config: PredictorConfig);
calibrate(predictions: number[], actuals: number[]): Promise<void>;
predict(pointPrediction: number): PredictionInterval;
update(pointPrediction: number, actual: number): Promise<void>;
setAlpha(alpha: number): void;
getAlpha(): number;
getMetrics(): Promise<PredictorMetrics>;
empiricalCoverage(): number;
}
AdaptiveConformalPredictor
class AdaptiveConformalPredictor {
constructor(config: AdaptiveConfig);
predictAndAdapt(
pointPrediction: number,
actual?: number
): Promise<PredictionInterval>;
empiricalCoverage(): number;
currentAlpha(): number;
getMetrics(): Promise<PredictorMetrics>;
}
PredictionInterval
interface PredictionInterval {
point: number;
lower: number;
upper: number;
alpha: number;
quantile: number;
timestamp: number;
width(): number;
contains(value: number): boolean;
relativeWidth(): number;
coverage(): number;
}
Configuration
interface PredictorConfig {
alpha: number;
scoreFunction: ScoreFunction;
calibrationSize?: number;
recalibrationFreq?: number;
maxIntervalWidthPct?: number;
monitoring?: {
enabled: boolean;
metricsInterval: number;
};
}
interface AdaptiveConfig {
targetCoverage: number;
gamma: number;
coverageWindow?: number;
alphaMin?: number;
alphaMax?: number;
scoreFunction: ScoreFunction;
}
Score Functions
import {
AbsoluteScore,
NormalizedScore,
QuantileScore,
} from '@neural-trader/predictor';
const absolute = new AbsoluteScore();
const normalized = new NormalizedScore({ epsilon: 1e-6 });
const quantile = new QuantileScore({ qLow: 0.05, qHigh: 0.95 });
🔗 Integration with @neural-trader/neural
Seamlessly combine neural predictions with conformal intervals:
import { NeuralPredictor } from '@neural-trader/neural';
import { wrapWithConformal } from '@neural-trader/predictor';
const neural = new NeuralPredictor({
modelPath: './model.onnx',
device: 'gpu',
});
const conformal = wrapWithConformal(neural, {
alpha: 0.1,
calibrationSize: 2000,
adaptive: true,
gamma: 0.02,
});
const features = loadFeatures();
const result = await conformal.predict(features);
console.log(`Point: ${result.point}`);
console.log(`Interval: [${result.lower}, ${result.upper}]`);
console.log(`Coverage: ${result.coverage() * 100}%`);
if (result.width() < 5 && result.point > 100) {
await executeOrder({
symbol: 'AAPL',
quantity: 100,
stopLoss: result.lower,
takeProfit: result.upper,
});
}
🎯 Trading Decision Engine
import { TradingDecisionEngine } from '@neural-trader/predictor';
const engine = new TradingDecisionEngine({
predictor: conformalPredictor,
maxIntervalWidthPct: 5.0,
minConfidence: 0.85,
kellyFraction: 0.25,
riskRewardRatio: 1.5,
});
const decision = await engine.evaluate(marketFeatures);
if (decision.shouldTrade) {
console.log(`Signal: ${decision.signal}`);
console.log(`Position Size: ${decision.positionSize}%`);
console.log(`Edge: ${decision.edge}%`);
console.log(`Risk: ${decision.risk}%`);
console.log(`Expected Sharpe: ${decision.expectedSharpe}`);
await executor.execute({
side: decision.signal,
quantity: decision.positionSize,
stopLoss: decision.stopLoss,
takeProfit: decision.takeProfit,
});
}
📊 Performance Monitoring
import { PredictorMonitor } from '@neural-trader/predictor';
const monitor = new PredictorMonitor(predictor);
setInterval(async () => {
const metrics = await monitor.getMetrics();
console.log(`
Coverage: ${(metrics.empiricalCoverage * 100).toFixed(2)}%
Avg Width: ${metrics.avgIntervalWidth.toFixed(4)}
Width Std Dev: ${metrics.widthStdDev.toFixed(4)}
Latency p50: ${metrics.latencyP50.toFixed(2)}ms
Latency p95: ${metrics.latencyP95.toFixed(2)}ms
Latency p99: ${metrics.latencyP99.toFixed(2)}ms
Calibration Age: ${metrics.calibrationAgeSeconds}s
`);
if (!monitor.isHealthy()) {
console.warn('⚠️ Predictor health issues:', monitor.getIssues());
if (metrics.calibrationAgeSeconds > 300) {
await recalibrate();
}
}
}, 5000);
🧪 Testing Utilities
import {
generateSyntheticData,
evaluateCoverage,
compareMethods,
performanceBenchmark,
} from '@neural-trader/predictor/testing';
const { predictions, actuals } = generateSyntheticData({
size: 10000,
distribution: 'normal',
noise: 0.1,
seed: 42,
});
const results = evaluateCoverage(predictor, predictions, actuals);
console.log(`Empirical Coverage: ${results.empiricalCoverage * 100}%`);
console.log(`Expected Coverage: ${(1 - predictor.alpha) * 100}%`);
console.log(`Avg Width: ${results.avgWidth}`);
const comparison = await compareMethods({
methods: ['conformal', 'bootstrap', 'mcDropout'],
testData: { predictions, actuals },
metrics: ['coverage', 'width', 'latency', 'memory'],
});
console.table(comparison);
const bench = await performanceBenchmark(predictor, {
iterations: 10000,
calibrationSizes: [1000, 2000, 5000],
memoryProfile: true,
});
console.log(`Throughput: ${bench.throughput} predictions/sec`);
console.log(`Memory Peak: ${bench.memoryPeak}MB`);
🌍 Browser Support
| Chrome | 90+ | ✓ Full support |
| Firefox | 88+ | ✓ Full support |
| Safari | 14+ | ✓ Full support |
| Edge | 90+ | ✓ Full support |
| Mobile (iOS) | 14+ | ✓ Full support |
| Mobile (Android) | 10+ | ✓ Full support |
WASM support requires browsers with WebAssembly support (all modern browsers).
📦 Build Targets
The package is built for multiple targets:
const { ConformalPredictor } = require('@neural-trader/predictor');
import { ConformalPredictor } from '@neural-trader/predictor';
import { WasmConformalPredictor } from '@neural-trader/predictor/wasm';
import { NativeConformalPredictor } from '@neural-trader/predictor/native';
🚀 Examples
See the /examples directory for complete working examples:
basic.ts - Simple conformal prediction
trading.ts - Real trading integration example
Run examples:
npm run build
npm run bench
🧠 Mathematical Background
Conformal Prediction Guarantee
For calibration samples with nonconformity scores:
Quantile = ceil((n+1)(1-α)) / n
Prediction interval guarantees:
P(y ∈ [pred - Quantile, pred + Quantile]) ≥ 1 - α
Adaptive Coverage (ACI)
Dynamically adjusts α using PID control:
α_new = α - γ × (observed_coverage - target_coverage)
With constraints: α_min ≤ α_new ≤ α_max
📝 Logging & Debugging
localStorage.setItem('log-level', 'debug');
process.env.DEBUG = 'neural-trader:*';
Log levels: error, warn, info, debug, trace
🔒 Error Handling
import { PredictionError, ConfigError, CalibrationError } from '@neural-trader/predictor';
try {
const interval = await predictor.predict(value);
} catch (error) {
if (error instanceof CalibrationError) {
console.error('Calibration failed:', error.message);
await recalibrate();
} else if (error instanceof ConfigError) {
console.error('Invalid configuration:', error.message);
} else if (error instanceof PredictionError) {
console.error('Prediction failed:', error.message);
}
}
🤝 Contributing
Contributions welcome! Please:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Run tests:
npm run test
- Format code:
npm run lint
- Submit a pull request
📄 License
Licensed under either of:
at your option.
🔗 Resources
⚡ Roadmap
💬 Support
For issues, questions, or suggestions:
Built with ❤️ for the quantitative trading and ML communities