or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

algorithm-components.mdbacktesting-engine.mdcore-framework.mdindex.mdspecialized-securities.md

index.mddocs/

0

# bt

1

2

A flexible backtesting framework for Python designed for quantitative trading strategy development and testing. bt uses a tree-structured approach with modular algorithmic components (Algos) for building complex trading strategies that are easily testable, reusable, and flexible.

3

4

## Package Information

5

6

- **Package Name**: bt

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install bt`

10

- **Documentation**: http://pmorissette.github.io/bt

11

12

## Core Imports

13

14

```python

15

import bt

16

```

17

18

Common import patterns:

19

20

```python

21

# Core framework classes

22

from bt import Strategy, Backtest, Security, Algo, AlgoStack

23

24

# Algorithm components

25

from bt.algos import SelectAll, WeighEqually, Rebalance, RunMonthly

26

27

# Backtesting utilities

28

from bt import run

29

```

30

31

## Basic Usage

32

33

```python

34

import bt

35

import pandas as pd

36

37

# Load sample data (bt integrates with ffn for data retrieval)

38

data = bt.get('SPY,TLT', start='2010-01-01', end='2020-01-01')

39

40

# Define a simple monthly rebalancing strategy

41

strategy = bt.Strategy('EqualWeight',

42

[bt.algos.RunMonthly(),

43

bt.algos.SelectAll(),

44

bt.algos.WeighEqually(),

45

bt.algos.Rebalance()])

46

47

# Create and run backtest

48

backtest = bt.Backtest(strategy, data)

49

result = bt.run(backtest)

50

51

# Display results

52

result.display()

53

result.plot()

54

```

55

56

## Architecture

57

58

bt's tree-structured design enables modular strategy construction:

59

60

- **Node**: Base building block for the tree structure, providing price tracking and hierarchy management

61

- **Strategy**: Tree node that defines strategy logic through algorithmic stacks

62

- **Security**: Tree node representing individual securities with position tracking

63

- **Algo**: Individual algorithmic building blocks that can be combined into stacks

64

- **AlgoStack**: Container for multiple algorithms executed sequentially

65

- **Backtest**: Combines strategy with data to produce results

66

67

This modular design allows complex strategies to be built from simple, reusable components while maintaining clear separation of concerns between data management, strategy logic, and execution.

68

69

## Capabilities

70

71

### Core Framework Classes

72

73

Fundamental building blocks for creating strategies and securities within bt's tree structure, including base classes, strategy containers, and security types.

74

75

```python { .api }

76

class Node:

77

def __init__(self, name: str, parent=None, children=None): ...

78

def setup(self, universe, **kwargs): ...

79

def update(self, date, data=None, inow=None): ...

80

81

class Strategy(StrategyBase):

82

def __init__(self, name: str, algos=None, children=None, parent=None): ...

83

def run(self): ...

84

85

class Security(SecurityBase):

86

def __init__(self, name: str, multiplier=1, lazy_add=False): ...

87

```

88

89

[Core Framework](./core-framework.md)

90

91

### Algorithm Components

92

93

Comprehensive library of 50+ algorithmic building blocks for strategy logic, organized into categories including execution control, security selection, weighting, portfolio management, and risk management.

94

95

```python { .api }

96

class Algo:

97

def __init__(self, name=None): ...

98

def __call__(self, target): ...

99

100

class AlgoStack(Algo):

101

def __init__(self, *algos): ...

102

103

# Key algorithm examples

104

class RunMonthly(RunPeriod): ...

105

class SelectAll(Algo): ...

106

class WeighEqually(Algo): ...

107

class Rebalance(Algo): ...

108

```

109

110

[Algorithm Components](./algorithm-components.md)

111

112

### Backtesting Engine

113

114

Core backtesting functionality for combining strategies with data, executing backtests, and analyzing results with comprehensive statistics and visualization capabilities.

115

116

```python { .api }

117

class Backtest:

118

def __init__(self, strategy, data, name=None, initial_capital=1000000.0,

119

commissions=None, integer_positions=True, progress_bar=False,

120

additional_data=None): ...

121

def run(self): ...

122

123

def run(*backtests): ...

124

125

class Result(ffn.GroupStats):

126

def display_monthly_returns(self, backtest=0): ...

127

def plot_weights(self, backtest=0, filter=None, figsize=(15, 5), **kwds): ...

128

```

129

130

[Backtesting Engine](./backtesting-engine.md)

131

132

### Specialized Securities

133

134

Advanced security types for specialized use cases including fixed income securities, hedge securities, and coupon-paying instruments with custom valuation and cash flow handling.

135

136

```python { .api }

137

class FixedIncomeSecurity(SecurityBase): ...

138

class HedgeSecurity(SecurityBase): ...

139

class CouponPayingSecurity(FixedIncomeSecurity): ...

140

class CouponPayingHedgeSecurity(CouponPayingSecurity): ...

141

class FixedIncomeStrategy(Strategy): ...

142

```

143

144

[Specialized Securities](./specialized-securities.md)

145

146

## Data Integration

147

148

bt integrates seamlessly with the ffn financial function library for data retrieval and manipulation:

149

150

```python { .api }

151

# Re-exported from ffn

152

def data(*args, **kwargs): ...

153

def get(*args, **kwargs): ...

154

def merge(*args, **kwargs): ...

155

utils # Module re-exported from ffn

156

```

157

158

## Constants

159

160

```python { .api }

161

__version__: str = "1.1.2"

162

PAR: float = 100.0 # Par value constant

163

TOL: float = 1e-16 # Tolerance for floating point comparisons

164

```