Skip to main content

Ultra-fast backtesting and trading framework. Built with Polars for speed, designed for simplicity.

Project description

wrtrade

Ultra-fast backtesting and trading framework. Built with Polars for speed, designed for simplicity.

Install

pip install wrtrade

Quick Start

import wrtrade as wrt
import polars as pl

# Define your signal
def trend(prices):
    fast = prices.rolling_mean(10)
    slow = prices.rolling_mean(30)
    return (fast > slow).cast(int) - (fast < slow).cast(int)

# One-line backtest
result = wrt.backtest(trend, prices)
print(f"Sortino: {result.sortino:.2f}")

That's it. No builders, no managers, no factories.

The API

Portfolio

Portfolio is the core data type. It holds trading signals.

# Single signal
portfolio = wrt.Portfolio(trend)

# Multiple signals with weights
portfolio = wrt.Portfolio([
    (trend, 0.6),
    (momentum, 0.4),
])

# Named signals
portfolio = wrt.Portfolio({
    'trend': (trend, 0.6),
    'momentum': (momentum, 0.4),
})

Backtest

# From a signal function
result = wrt.backtest(trend, prices)

# From a portfolio
result = portfolio.backtest(prices)

# Access metrics
result.sortino        # Sortino ratio
result.sharpe         # Sharpe ratio
result.max_drawdown   # Maximum drawdown
result.total_return   # Total return
result.volatility     # Annualized volatility
result.returns        # Returns series

# Print formatted report
result.tear_sheet()

Validate

Statistical validation using permutation testing:

# One-line validation
p_value = wrt.validate(trend, prices)

if p_value < 0.05:
    print("Strategy is statistically significant!")

# With more control
p_value = portfolio.validate(prices, n_permutations=1000, parallel=True)

Optimize

Kelly criterion optimization for position sizing:

# Optimize weights
portfolio.optimize(prices)

# With parameters
portfolio.optimize(prices, method='kelly', max_leverage=1.0)

Complete Example

import wrtrade as wrt
import polars as pl
import numpy as np

# 1. Define signals
def trend(prices):
    fast = prices.rolling_mean(10)
    slow = prices.rolling_mean(30)
    return (fast > slow).cast(int) - (fast < slow).cast(int)

def momentum(prices):
    returns = prices.pct_change(20).fill_null(0)
    return (returns > 0.05).cast(int) - (returns < -0.05).cast(int)

# 2. Create portfolio
portfolio = wrt.Portfolio([
    (trend, 0.6),
    (momentum, 0.4),
])

# 3. Backtest
result = portfolio.backtest(prices)
print(f"Sortino: {result.sortino:.2f}")
print(f"Return: {result.total_return:.2%}")

# 4. Validate
p_value = portfolio.validate(prices)
if p_value < 0.05:
    print("Strategy is significant!")

# 5. Optimize
portfolio.optimize(prices)
print(f"Optimized weights: {portfolio.weights}")

# 6. View report
result.tear_sheet()

Deployment

Create a strategy file with a build_portfolio() function:

# my_strategy.py
import wrtrade as wrt

def trend(prices):
    fast = prices.rolling_mean(10)
    slow = prices.rolling_mean(30)
    return (fast > slow).cast(int) - (fast < slow).cast(int)

def build_portfolio():
    return wrt.Portfolio(trend, name="Trend_Strategy")

Deploy:

wrtrade strategy deploy my_strategy.py \
    --name my_strategy \
    --broker alpaca \
    --symbols AAPL,TSLA

wrtrade strategy start my_strategy

Signal Functions

Signal functions take a price series and return signals:

def my_signal(prices: pl.Series) -> pl.Series:
    """
    Args:
        prices: Polars Series of prices

    Returns:
        Polars Series with values:
        -1 = short
         0 = flat
         1 = long
    """
    # Your logic here
    return signals

Advanced Usage

All advanced features remain accessible:

# Permutation testing with full control
from wrtrade import PermutationTester, PermutationConfig

config = PermutationConfig(
    n_permutations=5000,
    parallel=True,
    preserve_gaps=True,
)
tester = PermutationTester(config)
results = tester.run_walkforward_test(prices, strategy_func, train_window=252)

# Kelly optimization with parameters
from wrtrade import KellyOptimizer, KellyConfig

config = KellyConfig(
    lookback_window=252,
    max_leverage=1.0,
    min_weight=0.0,
    max_weight=1.0,
)
optimizer = KellyOptimizer(config)

CLI Reference

wrtrade strategy deploy <file>  # Deploy strategy
wrtrade strategy start <name>   # Start trading
wrtrade strategy stop <name>    # Stop trading
wrtrade strategy status         # Check status
wrtrade strategy logs <name>    # View logs

Why wrtrade?

  • Fast: Built on Polars, 10-50x faster than pandas
  • Simple: Portfolio is a data type, not a framework
  • Validated: Built-in permutation testing catches overfitting
  • Production-ready: CLI deployment with monitoring

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

wrtrade-2.1.0.tar.gz (87.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

wrtrade-2.1.0-py3-none-any.whl (74.8 kB view details)

Uploaded Python 3

File details

Details for the file wrtrade-2.1.0.tar.gz.

File metadata

  • Download URL: wrtrade-2.1.0.tar.gz
  • Upload date:
  • Size: 87.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for wrtrade-2.1.0.tar.gz
Algorithm Hash digest
SHA256 fdc2ffbdabcc2cee11f5c164197535e3289f6fae09f146a185a19f59b77ba025
MD5 87d7b0601e09cc99ce73b67d76f7d4ca
BLAKE2b-256 8840f8f43d083506c34c593a0228ede2f29ef3eb01b7597566d2499fb73aa8b7

See more details on using hashes here.

Provenance

The following attestation bundles were made for wrtrade-2.1.0.tar.gz:

Publisher: publish.yml on Wayy-Research/wrtrade

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file wrtrade-2.1.0-py3-none-any.whl.

File metadata

  • Download URL: wrtrade-2.1.0-py3-none-any.whl
  • Upload date:
  • Size: 74.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for wrtrade-2.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 cf83530e5d0cab43a200f3b781526ff61dfcf6dc169fb60fe2005ede8c6835ce
MD5 5d9c01b41e4b040d155af99c03cf9e01
BLAKE2b-256 ac14ccf12f4dcfe890800369089e6b4c0dafacb0f510c86b7a06175c10eddecd

See more details on using hashes here.

Provenance

The following attestation bundles were made for wrtrade-2.1.0-py3-none-any.whl:

Publisher: publish.yml on Wayy-Research/wrtrade

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page