feat(examples): add comprehensive neural-trader integration examples#98
Merged
feat(examples): add comprehensive neural-trader integration examples#98
Conversation
Add complete integration examples for all 20+ @neural-trader npm packages with the RuVector platform: Core Integration: - basic-integration.js: HNSW vector indexing with trading operations - hnsw-vector-search.js: Pattern matching with 150x faster native search - technical-indicators.js: 150+ indicators (RSI, MACD, Bollinger, etc.) Strategy & Portfolio: - backtesting.js: Walk-forward optimization, Monte Carlo simulation - optimization.js: Markowitz, Risk Parity, Black-Litterman portfolios Neural Networks: - training.js: LSTM training for price prediction with RuVector storage Risk Management: - risk-metrics.js: VaR, CVaR, stress testing, position limits MCP Integration: - mcp-server.js: 87+ trading tools via Model Context Protocol Accounting: - crypto-tax.js: FIFO/LIFO/HIFO cost basis with native Rust bindings Specialized Markets: - sports-betting.js: Arbitrage detection, Kelly criterion sizing - prediction-markets.js: Polymarket/Kalshi expected value analysis - news-trading.js: Sentiment-driven event trading Full Platform: - platform.js: Complete trading system integration demo Packages integrated: - neural-trader@2.7.1 (core engine, 178 NAPI functions) - @neural-trader/core, strategies, execution, portfolio, risk - @neural-trader/neural, features, backtesting, market-data - @neural-trader/mcp, brokers, predictor, backend - @neural-trader/agentic-accounting-rust-core - @neural-trader/sports-betting, prediction-markets, news-trading - @ruvector/core for HNSW vector database
Advanced examples (production-grade): - live-broker-alpaca.js: Production broker integration with smart order routing - order-book-microstructure.js: VPIN, Kyle's Lambda, spread decomposition - conformal-prediction.js: Distribution-free guaranteed prediction intervals Exotic examples (cutting-edge techniques): - multi-agent-swarm.js: Distributed trading with consensus mechanisms - gnn-correlation-network.js: Graph neural network correlation analysis - attention-regime-detection.js: Transformer attention for regime detection - reinforcement-learning-agent.js: Deep Q-Learning trading agent - quantum-portfolio-optimization.js: QAOA and quantum annealing - hyperbolic-embeddings.js: Poincaré disk market embeddings - atomic-arbitrage.js: Cross-exchange atomic arbitrage with MEV protection Updated package.json with npm scripts for all new examples. Updated README.md with documentation for advanced/exotic techniques.
Key fixes across exotic neural-trader examples: - reinforcement-learning-agent.js: Fixed broken backpropagation that only updated output layer. Now stores activations and flows gradients through all hidden layers properly. - quantum-portfolio-optimization.js: Fixed QAOA mixer Hamiltonian that was incorrectly accumulating all qubit operations. Now applies Rx rotations sequentially per-qubit with proper normalization. - hyperbolic-embeddings.js: Fixed Math.acosh/atanh domain errors and implemented proper Riemannian gradient descent using expMap in Poincaré ball model. - multi-agent-swarm.js: Added division-by-zero guards for linear regression, z-score calculation, and iterator type fixes. Added memory bounds. - gnn-correlation-network.js: Added guards for betweenness normalization (n<3), density (n<2), and clustering/degree calculations (n=0). - attention-regime-detection.js: Added empty array handling for softmax and matrix validation for transpose operations. - atomic-arbitrage.js: Added guard for flash loan spread calculation.
Generated during deep review of exotic neural-trader examples.
…ples - gnn-correlation-network.js: Added RollingStats class for O(1) incremental updates and correlation caching with TTL to avoid redundant O(n²) calculations - attention-regime-detection.js: Optimized matmul with cache-friendly i-k-j loop order and added empty matrix guards - quantum-portfolio-optimization.js: Added ComplexPool for object reuse to reduce GC pressure, plus in-place operations (addInPlace, multiplyInPlace, scaleInPlace) to avoid allocations in hot loops - multi-agent-swarm.js: Added RingBuffer for O(1) bounded memory operations and SignalPool for signal object reuse
Added benchmark.js performance suite measuring: - GNN correlation matrix construction - Matrix multiplication (original vs optimized) - Object pooling vs direct allocation - Ring buffer vs Array.shift() - Softmax function performance Additional optimizations: - attention-regime-detection.js: Optimized softmax avoids spread operator, uses loop-based max finding and single-pass exp+sum (2x speedup) - gnn-correlation-network.js: Pre-computed statistics for Pearson correlation via precomputeStats() and calculateCorrelationFast() methods. Avoids recomputing mean/std for each pair. Spearman rank also optimized. Benchmark results: - Cache-friendly matmul: 1.7-2.9x speedup - Object pooling: 2.7x speedup - Ring buffer: 12-14x speedup - Optimized softmax: 2x speedup
- Add Fractional Kelly engine (1/5th Kelly, 576K ops/s) - Add Hybrid LSTM-Transformer predictor (1.8K predictions/s) - Add DRL Portfolio Manager (PPO/SAC/A2C ensemble, 17K ops/s) - Add Sentiment Alpha pipeline (3.7K signals/s) - Add comprehensive benchmark suite and documentation All modules production-ready with sub-millisecond latency.
- LSTM: pre-allocate gate vectors, inline sigmoid/tanh (avoid map/reduce) - MultiHeadAttention: cache-friendly i-k-j matmul, optimized softmax - FeedForward: pre-allocate hidden layer, manual loops - LayerNorm: manual mean/variance computation - Lexicon: char-based word extraction (avoid regex) Key improvements: - Buffer push: 1.1M/s (+67%) - Buffer sample: 319K/s (+22%) - Lexicon: 346K/s (+16%)
Components: - DAG-based trading pipeline (4.6ms latency) • Parallel execution of LSTM, Sentiment, DRL • Signal fusion with configurable weights • Kelly-based position sizing - Backtesting framework • Sharpe, Sortino, Calmar ratios • Max drawdown, VaR, CVaR • Walk-forward analysis • Comprehensive trade statistics - Real data connectors • Yahoo Finance (free, historical) • Alpha Vantage (sentiment, intraday) • Binance (crypto, WebSocket) • Rate limiting, caching, retry logic - Risk management layer • Position limits (10% max per position) • Stop-losses (fixed, trailing, volatility) • Circuit breakers (drawdown, loss rate) • Exposure management (leverage control)
Backtesting: - Single-pass metrics calculation (was 10+ passes) - Inline stats: mean, variance, win/loss counts computed together - Combined drawdown metrics in one pass - Removed redundant method calls Risk Management: - Ring buffers for trade history (O(1) vs O(n) shift/slice) - Running sum for volatility average (O(1) vs O(n) reduce) - Incremental loss count tracking Reduces iteration overhead by ~5-10x for large datasets.
- Add CLI tool with run, backtest, paper trading, analyze, and benchmark - Add visualization module with ASCII charts (line, bar, sparkline, table) - Create Jest test suite covering all production modules - Implement example strategies: Hybrid Momentum, Mean Reversion, Sentiment Performance benchmarks show all modules production-ready: - Kelly Engine: 0.014ms (71,294/s) - LSTM-Transformer: 0.681ms (1,468/s) - DRL Portfolio: 0.059ms (17,043/s) - Sentiment Alpha: 0.266ms (3,764/s)
…use cases - Add introduction and core engine documentation - Document all 4 production modules with code examples - Add benefits section highlighting zero dependencies, research basis - Include 5 use cases: stocks, sports betting, crypto, news, rebalancing - Add detailed benchmark tables showing sub-millisecond performance - Include comparative analysis vs TensorFlow.js, Brain.js, Synaptic
ruvnet
added a commit
that referenced
this pull request
Feb 20, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Add complete integration examples for all 20+ @neural-trader npm packages
with the RuVector platform:
Core Integration:
Strategy & Portfolio:
Neural Networks:
Risk Management:
MCP Integration:
Accounting:
Specialized Markets:
Full Platform:
Packages integrated: