Convert Figma logo to code with AI

pmorissette logobt

bt - flexible backtesting for Python

2,983
501
2,983
13

Top Related Projects

19,995

Zipline, a Pythonic Algorithmic Trading Library

24,764

Download market data from Yahoo! Finance's API

20,638

Lean Algorithmic Trading Engine by QuantConnect (Python, C#)

An Algorithmic Trading Library for Crypto-Assets in Python

Python Backtesting library for trading strategies

Python library for backtesting trading strategies & analyzing financial markets (formerly pythalesians)

Quick Overview

bt (Backtesting) is a Python library for backtesting quantitative trading strategies. It provides a flexible framework for defining and testing trading strategies, portfolio management, and performance analysis. The library is designed to be intuitive and easy to use, while still offering powerful features for advanced users.

Pros

  • Flexible and extensible architecture for creating custom trading strategies
  • Built-in support for various data sources, including CSV files and Pandas DataFrames
  • Comprehensive set of performance metrics and visualization tools
  • Integration with popular financial libraries like pandas and ffn

Cons

  • Limited documentation and examples for advanced features
  • Steeper learning curve compared to some other backtesting libraries
  • May require additional libraries for certain functionalities (e.g., plotting)
  • Performance can be slower for large datasets or complex strategies

Code Examples

  1. Creating a simple moving average crossover strategy:
import bt

# Define the strategy
class SmaCross(bt.Strategy):
    def __init__(self, short_period=10, long_period=30):
        super().__init__()
        self.short_period = short_period
        self.long_period = long_period

    def __call__(self, target):
        data = target.universe.loc[:, target.name]
        short_sma = data.rolling(self.short_period).mean()
        long_sma = data.rolling(self.long_period).mean()
        return short_sma > long_sma

# Create and run the backtest
data = bt.get('aapl,msft', start='2010-01-01')
strategy = bt.Strategy('SmaCross', [SmaCross()])
backtest = bt.Backtest(strategy, data)
result = bt.run(backtest)
  1. Analyzing backtest results:
# Display performance metrics
print(result.display())

# Plot equity curve
result.plot()

# Generate trade statistics
print(result.trade_stats)
  1. Creating a multi-asset portfolio with rebalancing:
import bt

# Define the strategy
strategy = bt.Strategy('RebalanceStrategy',
    [bt.algos.RunMonthly(),
     bt.algos.SelectAll(),
     bt.algos.WeighEqually(),
     bt.algos.Rebalance()])

# Create and run the backtest
data = bt.get('spy,agg,eem,iwm', start='2010-01-01')
backtest = bt.Backtest(strategy, data)
result = bt.run(backtest)

Getting Started

To get started with bt, follow these steps:

  1. Install the library:

    pip install bt
    
  2. Import the library and load some data:

    import bt
    data = bt.get('aapl,msft', start='2020-01-01')
    
  3. Create a simple strategy:

    strategy = bt.Strategy('BuyAndHold', [bt.algos.RunOnce(),
                                          bt.algos.SelectAll(),
                                          bt.algos.WeighEqually(),
                                          bt.algos.Rebalance()])
    
  4. Run the backtest and analyze results:

    backtest = bt.Backtest(strategy, data)
    result = bt.run(backtest)
    print(result.display())
    result.plot()
    

Competitor Comparisons

19,995

Zipline, a Pythonic Algorithmic Trading Library

Pros of Zipline

  • More comprehensive and feature-rich backtesting framework
  • Larger community and ecosystem, with better documentation
  • Integrated with Quantopian's research platform (when it was active)

Cons of Zipline

  • Steeper learning curve due to its complexity
  • Slower performance for simple backtests
  • Less actively maintained since Quantopian's shutdown

Code Comparison

Zipline example:

from zipline.api import order, record, symbol

def initialize(context):
    context.asset = symbol('AAPL')

def handle_data(context, data):
    order(context.asset, 10)
    record(AAPL=data.current(context.asset, 'price'))

bt example:

import bt

data = bt.get('aapl', start='2010-01-01')
s = bt.Strategy('s1', [bt.algos.RunMonthly(),
                       bt.algos.SelectAll(),
                       bt.algos.WeighEqually(),
                       bt.algos.Rebalance()])
test = bt.Backtest(s, data)
res = bt.run(test)

Summary

While Zipline offers a more comprehensive backtesting framework with a larger ecosystem, bt provides a simpler and more lightweight alternative. Zipline excels in complex scenarios but has a steeper learning curve, whereas bt is easier to use for basic backtests and offers faster performance for simple strategies. The choice between the two depends on the specific requirements of your backtesting project and your familiarity with Python and financial modeling.

24,764

Download market data from Yahoo! Finance's API

Pros of yfinance

  • Focused specifically on fetching financial data from Yahoo Finance
  • Simpler API for retrieving stock data and information
  • More actively maintained with frequent updates

Cons of yfinance

  • Limited to Yahoo Finance as a data source
  • Lacks advanced backtesting and portfolio analysis features
  • May experience occasional issues due to changes in Yahoo Finance's API

Code Comparison

yfinance:

import yfinance as yf

ticker = yf.Ticker("AAPL")
hist = ticker.history(period="1mo")
print(hist)

bt:

import bt

data = bt.get('aapl,msft', start='2010-01-01')
s = bt.Strategy('s1', [bt.algos.RunMonthly(),
                       bt.algos.SelectAll(),
                       bt.algos.WeighEqually(),
                       bt.algos.Rebalance()])
test = bt.Backtest(s, data)
res = bt.run(test)

Summary

yfinance is a specialized library for fetching financial data from Yahoo Finance, offering a straightforward API for retrieving stock information. It's actively maintained but limited to a single data source. bt, on the other hand, provides a more comprehensive toolkit for backtesting and portfolio analysis, supporting multiple data sources and offering advanced features for strategy development and evaluation.

20,638

Lean Algorithmic Trading Engine by QuantConnect (Python, C#)

Pros of Lean

  • More comprehensive and production-ready algorithmic trading platform
  • Supports multiple asset classes and markets
  • Offers cloud-based backtesting and live trading capabilities

Cons of Lean

  • Steeper learning curve due to its complexity
  • Requires more setup and configuration compared to bt
  • Less flexible for quick, simple backtests

Code Comparison

bt:

bt.run(
    bt.Strategy('s1', [bt.algos.SelectAll(),
                       bt.algos.WeighEqually(),
                       bt.algos.Rebalance()]),
    data
)

Lean:

public class MyAlgorithm : QCAlgorithm
{
    public override void Initialize()
    {
        SetStartDate(2010, 1, 1);
        SetCash(100000);
        AddEquity("SPY", Resolution.Daily);
    }
}

bt focuses on simplicity and ease of use for backtesting, allowing users to quickly set up and run strategies with minimal code. Lean, on the other hand, provides a more structured and comprehensive approach, requiring more setup but offering greater flexibility and features for production-ready algorithmic trading systems.

An Algorithmic Trading Library for Crypto-Assets in Python

Pros of Catalyst

  • Focuses on privacy-preserving computations and secure multi-party computation
  • Provides tools for building decentralized applications on the Secret Network
  • Offers advanced cryptographic features like zero-knowledge proofs

Cons of Catalyst

  • More complex setup and learning curve due to its focus on privacy and cryptography
  • Limited to the Secret Network ecosystem, potentially reducing broader applicability
  • May have fewer general-purpose backtesting features compared to bt

Code Comparison

bt:

bt.run(
    strategy,
    data=data,
    initial_capital=10000,
    commission=0.002
)

Catalyst:

run_algorithm(
    initialize=initialize,
    handle_data=handle_data,
    analyze=analyze,
    exchange_name='poloniex',
    base_currency='usdt'
)

Summary

bt is a flexible backtesting framework for Python, suitable for various financial strategies. Catalyst specializes in privacy-preserving computations on the Secret Network. While bt offers a more general-purpose solution for backtesting, Catalyst provides unique features for building decentralized applications with advanced cryptographic capabilities. The choice between them depends on the specific requirements of the project and the desired ecosystem.

Python Backtesting library for trading strategies

Pros of Backtrader

  • More extensive documentation and examples
  • Larger community and ecosystem of add-ons
  • Built-in support for live trading and multiple data feeds

Cons of Backtrader

  • Steeper learning curve due to more complex architecture
  • Slower performance for large datasets or complex strategies
  • Less flexibility in customizing plotting and reporting

Code Comparison

Backtrader:

class MyStrategy(bt.Strategy):
    def __init__(self):
        self.sma = bt.indicators.SimpleMovingAverage(self.data.close, period=20)

    def next(self):
        if self.data.close[0] > self.sma[0]:
            self.buy()
        elif self.data.close[0] < self.sma[0]:
            self.sell()

bt:

def my_strategy(algo, data):
    sma = data.close.rolling(20).mean()
    if data.close > sma:
        algo.buy()
    elif data.close < sma:
        algo.sell()

Both libraries offer powerful backtesting capabilities, but Backtrader provides a more comprehensive framework with additional features for live trading and multiple data feeds. However, bt offers a simpler API and better performance for large datasets. The choice between the two depends on the specific requirements of your trading strategy and the level of complexity you're comfortable with.

Python library for backtesting trading strategies & analyzing financial markets (formerly pythalesians)

Pros of finmarketpy

  • More comprehensive financial market analysis tools, including FX, fixed income, and crypto
  • Actively maintained with recent updates and contributions
  • Includes data visualization capabilities

Cons of finmarketpy

  • Steeper learning curve due to more complex features
  • Less focused on backtesting compared to bt
  • Smaller community and fewer resources available online

Code Comparison

bt:

import bt
data = bt.get('spy,agg', start='2010-01-01')
s = bt.Strategy('s1', [bt.algos.RunMonthly(),
                       bt.algos.SelectAll(),
                       bt.algos.WeighEqually(),
                       bt.algos.Rebalance()])
test = bt.Backtest(s, data)
res = bt.run(test)

finmarketpy:

from finmarketpy.backtest import Backtest, BacktestRequest
from finmarketpy.economics import Market
market = Market(market_data=['SPY', 'AGG'])
br = BacktestRequest(start_date='01 Jan 2010', finish_date='31 Dec 2020',
                     strategy_name='EqualWeight')
backtest = Backtest()
results = backtest.run_backtest(br, market)

Both libraries offer backtesting capabilities, but bt focuses more on simplicity and ease of use, while finmarketpy provides a broader range of financial market analysis tools. The code examples demonstrate that bt has a more concise syntax for basic backtesting, while finmarketpy requires more setup but offers greater flexibility for complex scenarios.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

bt — Flexible Backtesting for Python

Build Status PyPI Version PyPI License

Build, test, and compare investment strategies from reusable Python components. bt combines strategy logic with historical price data, tracks portfolio positions and transactions, and provides performance statistics and charts through ffn.

  • Compose strategy logic: combine algorithms for scheduling, security selection, weighting, and rebalancing.
  • Build portfolios of strategies: nest strategies and securities in a common tree.
  • Model trading costs: configure commissions and transaction cost models.
  • Compare results: inspect returns, weights, transactions, drawdowns, and other statistics.

Install

pip install bt

See the installation guide for additional details.

A first backtest

This example uses synthetic prices, so it runs without downloading market data:

import numpy as np
import pandas as pd

import bt

prices = pd.DataFrame(
    {
        "asset_a": np.linspace(100, 120, 252),
        "asset_b": np.linspace(100, 110, 252),
    },
    index=pd.bdate_range("2020-01-01", periods=252),
)

strategy = bt.Strategy(
    "equal_weight",
    [
        bt.algos.RunMonthly(),
        bt.algos.SelectAll(),
        bt.algos.WeighEqually(),
        bt.algos.Rebalance(),
    ],
)
result = bt.run(bt.Backtest(strategy, prices))
result.display()

The strategy selects both assets, gives each equal weight, and rebalances monthly. Replace the synthetic prices with your own data to explore a strategy. Backtest results depend on data quality and modeling assumptions; they do not predict future performance.

Explore the documentation

The published documentation is at https://pmorissette.github.io/bt/.

Contribute

See the development guide for environment setup, tests, documentation builds, and Copier template updates. Report bugs and propose improvements through GitHub issues.

bt is released under the MIT license.