A flexible backtesting framework for Python designed for quantitative trading strategy development and testing.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Fundamental building blocks for creating strategies and securities within bt's tree structure. These classes provide the foundation for bt's modular design, enabling the construction of complex trading strategies through hierarchical composition of nodes.
The fundamental building block of bt's tree structure, providing price tracking, hierarchy management, and core functionality shared by all tree components.
class Node:
"""
Base tree node class for bt's hierarchical structure.
Args:
name (str): Name of the node
parent (Node, optional): Parent node in tree hierarchy
children (list, optional): List of child nodes
"""
def __init__(self, name: str, parent=None, children=None): ...
def setup(self, universe, **kwargs):
"""Setup node with data universe and configuration."""
...
def update(self, date, data=None, inow=None):
"""Update node state for given date."""
...
def adjust(self, amount, update=True, flow=True):
"""Adjust node value by specified amount."""
...
def allocate(self, amount, update=True):
"""Allocate capital to this node."""
...
def to_dot(self, root=True):
"""Generate graphviz representation of tree structure."""
...
# Properties
@property
def name(self) -> str: ...
@property
def parent(self): ...
@property
def root(self): ...
@property
def children(self) -> list: ...
@property
def now(self): ...
@property
def stale(self) -> bool: ...
@property
def prices(self): ...
@property
def price(self): ...
@property
def value(self): ...
@property
def notional_value(self): ...
@property
def weight(self): ...
@property
def full_name(self) -> str: ...
@property
def members(self) -> list: ...
@property
def fixed_income(self) -> bool: ...Base class for strategy nodes that define strategy logic within the tree structure, providing core functionality for portfolio management and algorithmic execution.
class StrategyBase(Node):
"""
Strategy base class inheriting from Node.
Args:
name (str): Strategy name
children (list, optional): Child nodes (securities/sub-strategies)
parent (Node, optional): Parent node
"""
def __init__(self, name: str, children=None, parent=None): ...
def setup(self, universe, **kwargs):
"""Setup strategy with universe data and configuration."""
...
def get_data(self, key):
"""Get data by key from universe."""
...
def update(self, date, data=None, inow=None):
"""Update strategy state for given date."""
...
def adjust(self, amount, update=True, flow=True, fee=0.0):
"""Adjust strategy value with optional fee."""
...
def allocate(self, amount, child=None, update=True):
"""Allocate capital to specific child or distribute among children."""
...
def transact(self, q, child=None, update=True):
"""Execute transaction for specific child."""
...
def rebalance(self, weight, child, base=float('nan'), update=True):
"""Rebalance position in specific child to target weight."""
...
def close(self, child, update=True):
"""Close position in specific child."""
...
def flatten(self):
"""Close all positions in strategy."""
...
def run(self):
"""Execute strategy logic."""
...
def set_commissions(self, fn):
"""Set commission calculation function."""
...
def get_transactions(self):
"""Get transaction history for strategy."""
...
# Properties
@property
def prices(self): ...
@property
def price(self): ...
@property
def values(self): ...
@property
def notional_values(self): ...
@property
def capital(self): ...
@property
def cash(self): ...
@property
def fees(self): ...
@property
def flows(self): ...
@property
def bidoffer_paid(self): ...
@property
def bidoffers_paid(self): ...
@property
def universe(self): ...
@property
def securities(self): ...
@property
def outlays(self): ...
@property
def positions(self): ...Base class for security nodes representing individual securities with position tracking, transaction execution, and commission handling.
class SecurityBase(Node):
"""
Security base class inheriting from Node.
Args:
name (str): Security name/ticker
multiplier (float): Security multiplier (default 1)
lazy_add (bool): Whether to add to parent lazily
"""
def __init__(self, name: str, multiplier=1, lazy_add=False): ...
def setup(self, universe, **kwargs):
"""Setup security with universe data."""
...
def update(self, date, data=None, inow=None):
"""Update security state for given date."""
...
def allocate(self, amount, update=True):
"""Allocate capital to this security."""
...
def transact(self, q, update=True, update_self=True, price=None):
"""Execute transaction for specified quantity."""
...
def commission(self, q, p):
"""Calculate commission for transaction."""
...
def outlay(self, q, p=None):
"""Calculate total outlay for transaction including commission."""
...
def run(self):
"""Execute security updates."""
...
# Properties
@property
def prices(self): ...
@property
def price(self): ...
@property
def values(self): ...
@property
def notional_values(self): ...
@property
def position(self): ...
@property
def positions(self): ...
@property
def outlays(self): ...
@property
def bidoffer(self): ...
@property
def bidoffers(self): ...
@property
def bidoffer_paid(self): ...
@property
def bidoffers_paid(self): ...The primary strategy class that incorporates algorithmic logic through algorithm stacks, with temporary and permanent data storage for cross-algorithm communication.
class Strategy(StrategyBase):
"""
Main strategy class incorporating algorithms.
Args:
name (str): Strategy name
algos (list, optional): List of algorithms to execute
children (list, optional): Child nodes
parent (Node, optional): Parent node
"""
def __init__(self, name: str, algos=None, children=None, parent=None): ...
def run(self):
"""Run strategy with algorithm stack execution."""
...
# Properties
@property
def stack(self): ... # Algorithm stack
@property
def temp(self): ... # Temporary data storage
@property
def perm(self): ... # Permanent data storageStandard security implementation with market value-based notional value calculation, suitable for most equity and ETF trading strategies.
class Security(SecurityBase):
"""
Standard security with market value-based notional value.
Inherits all methods and properties from SecurityBase.
Notional value equals market value (price * position).
"""
passBase classes for creating custom algorithmic components that can be combined into strategy logic.
class Algo:
"""
Base algorithm class for strategy building blocks.
Args:
name (str, optional): Algorithm name
"""
def __init__(self, name=None): ...
def __call__(self, target):
"""Execute algorithm logic on target strategy (abstract method)."""
...
@property
def name(self) -> str: ...
class AlgoStack(Algo):
"""
Algorithm container that runs multiple algorithms sequentially.
Args:
*algos: Variable number of algorithm instances
"""
def __init__(self, *algos): ...
def __call__(self, target):
"""Execute all algorithms in stack until one fails."""
...def is_zero(x) -> bool:
"""
Test for zero robust against floating point errors.
Args:
x: Value to test
Returns:
bool: True if value is effectively zero
"""
...PAR: float = 100.0 # Par value constant for fixed income
TOL: float = 1e-16 # Tolerance for floating point zero comparisonimport bt
# Create securities
spy = bt.Security('SPY')
tlt = bt.Security('TLT')
# Create strategy with securities as children
strategy = bt.Strategy('EqualWeight', children=[spy, tlt])
# Or add securities after creation
strategy = bt.Strategy('EqualWeight')
strategy.children = [spy, tlt]# Create individual algorithms
select_all = bt.algos.SelectAll()
weigh_equally = bt.algos.WeighEqually()
rebalance = bt.algos.Rebalance()
# Combine into algorithm stack
algo_stack = bt.AlgoStack(select_all, weigh_equally, rebalance)
# Use in strategy
strategy = bt.Strategy('MyStrategy', algos=[algo_stack])Install with Tessl CLI
npx tessl i tessl/pypi-bt