Skip to content

trenki2/NStrat

Repository files navigation

NStrat

A simple and high-performance algorithmic trading backtesting framework for .NET, designed for portfolio based strategy development using market orders.

Features

  • Multi-Asset Support - Trade multiple assets at once
  • Multi-Strategy Framework - Run multiple trading strategies simultaneously with independent or coordinated execution
  • Composable Nested Sub-Strategies - Build complex hierarchical strategies by nesting and combining simpler strategies
  • Nested Backtests - Run backtests within backtests for meta-strategy development and validation
  • Online Portfolio Optimization - Real-time portfolio allocation using FixedShare and ExponentiatedGradient algorithms
  • Comprehensive Analytics - Built-in performance metrics, drawdown analysis, and Sharpe ratio calculation
  • Flexible Scheduling - Event-driven execution with calendar integration
  • Realistic Market Simulation - Configurable spreads, commissions, and market impact models
  • Risk Management - Position sizing, leverage controls, and portfolio constraints

Quick Start

Installation

git clone https://github.com/trenki2/NStrat.git
cd NStrat
dotnet build

Basic Strategy Example

using NStrat.Core;
using NStrat.Core.Securities;
using NStrat.Core.Technical;

namespace NStrat.Strategies.Basic
{
    public class RsiLowHigh(SecurityId sid, int period, double low, double high) : Strategy
    {
        public int Lookback { get; init; } = 42;

        protected override void OnInitialize()
        {
            Benchmark = AddSecurity(sid);
        }

        protected override void OnUpdate()
        {
            var close = Benchmark!.GetHistory().Close.TakeLast(Lookback).ToArray();
            var rsi = TA.Rsi(close, period)[^1];
            if (rsi < low)
                OrderTargetPercent(Benchmark, 1);
            else if (rsi > high)
                OrderTargetPercent(Benchmark, 0);
        }
    }
}

Strategy Examples

The repository includes several example strategies demonstrating different approaches:

  • Example1 - Multi-strategy allocation with Buy-and-Hold and RSI
  • Example2 - Tech stock portfolio with dynamic rebalancing
  • Example3 - Sector rotation using momentum ranking

Core Components

Strategy Framework

  • Strategy - Base class for all trading strategies
  • FixedShare - Dynamic portfolio allocation algorithm
  • ApplyPortfolio - Executes portfolio allocation decisions
  • Stats - Performance tracking and analytics

Market Data & Execution

  • TradingCalendar - Market schedule and holiday handling
  • SpreadModel - Bid-ask spread simulation
  • CommissionModel - Transaction cost modeling
  • Broker - Order execution and portfolio management

Technical Indicators

  • Moving averages, RSI, momentum indicators
  • Crossover signals and trend detection
  • Custom indicator development framework

Configuration

Backtest Setup

SetStartDate(new DateTime(2020, 1, 1));
SetEndDate(DateTime.Today);
SetCash(100000);
Benchmark = AddEquity("SPY");

Market Structure

TradingCalendar = new UsaEquityTradingCalendar();
SpreadModel = new RelativeSpread(0.001m);  // 0.1% spread
CommissionModel = new PerTradeVolumeCommission(0.001m);  // $0.001 per share

Performance Analytics

NStrat provides comprehensive performance metrics:

  • Returns Analysis - Total return, annualized return, volatility
  • Risk Metrics - Maximum drawdown, Sharpe ratio, Sortino ratio
  • Portfolio Analytics - Leverage, concentration, turnover
  • Regime Detection - Market trend and volatility analysis

Advanced Features

Multi-Strategy Composition & Nesting

Build complex hierarchical strategies by composing and nesting simpler components:

var strategy1 = new BuyAndHold("QQQ");
var strategy2 = new RsiLowHigh("QQQ", 2, 25, 75);
var level1 = new FixedShare(strategy1, strategy2);

var strategy3 = new SectorRotation(sectorETFs);
var level2 = new ExponentiatedGradient(level1, strategy3);

AddSubStrategy(new ApplyPortfolio(level2));

Online Portfolio Optimization

Real-time adaptive allocation using state-of-the-art algorithms:

// FixedShare: Maintains fixed fraction of wealth in each strategy
var fixedShare = new FixedShare(strategies) { 
    Eta = 50,        // Learning rate
    Alpha = 1e-4     // Regularization
};

// ExponentiatedGradient: Multiplicative weight updates
var expGrad = new ExponentiatedGradient(strategies) {
    Eta = 0.1
};

Dynamic Rebalancing

Control rebalancing frequency and transaction costs:

var monthlyRebalance = new UpdateRate(strategy, 21);  // Rebalance every 21 days
var stats = new Stats(monthlyRebalance);

Custom Scheduling

Execute strategies on flexible schedules:

Schedule.On(DateRules.MonthStart(TradingCalendar), 
           TimeRules.At(9, 30, 0, TimeZones.Est), 
           MonthlyRebalance);

Requirements

  • .NET 8.0 or later
  • Visual Studio 2022 or VS Code
  • Windows

License

This project is licensed under the GNU Affero General Public License v3.0 - see the LICENSE file for details.

Disclaimer

This software is for educational and research purposes only. Past performance does not guarantee future results. Always consult with qualified financial professionals before making investment decisions.