CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-vectorbt

Python library for backtesting and analyzing trading strategies at scale

Pending
Overview
Eval results
Files

records-management.mddocs/

Records Management

Core record classes for managing and analyzing trading data including orders, trades, positions, and drawdowns with efficient sparse data structures. The records module provides the foundation for VectorBT's high-performance backtesting and analysis capabilities.

Core Imports

from vectorbt import Records, MappedArray
from vectorbt.records import Orders, Trades, Positions, Drawdowns

Capabilities

Base Record Classes

Core classes for managing and analyzing record-based data with efficient sparse storage and vectorized operations.

class Records:
    """
    Base class for all record types in VectorBT.
    
    Provides common functionality for record storage, filtering, and analysis
    with efficient memory usage and vectorized operations.
    """
    
    @property
    def records_arr(self):
        """Get underlying structured array of records."""
    
    def filter_by_mask(self, mask, **kwargs):
        """
        Filter records by boolean mask.
        
        Parameters:
        - mask: array-like, boolean mask for filtering records
        
        Returns:
        Records: Filtered records instance
        """
    
    def apply_mask(self, mask, **kwargs):
        """Apply boolean mask to records."""
    
    def count(self):
        """Count total number of records."""
    
    def map_field(self, field, **kwargs):
        """Map record field to output array."""

class MappedArray:
    """
    Efficient array structure for sparse data storage.
    
    Maps record indices to array positions enabling efficient storage
    and retrieval of sparse trading data.
    """
    
    @property
    def id_arr(self):
        """Array of indices."""
    
    @property
    def col_arr(self):
        """Array of column indices."""
    
    @property
    def values(self):
        """Array of values."""
    
    def map_to_mask(self, **kwargs):
        """Map values to boolean mask."""
    
    def to_pd(self, **kwargs):
        """Convert to pandas Series or DataFrame."""

Order Records

Management and analysis of order execution records with detailed order-level information.

class Orders(Records):
    """
    Order execution records management.
    
    Stores and analyzes order-level information including size, price,
    fees, and execution details for comprehensive trade analysis.
    """
    
    @property
    def size(self):
        """Order sizes (positive for buy, negative for sell)."""
    
    @property
    def price(self):
        """Order execution prices."""
    
    @property
    def fees(self):
        """Order execution fees."""
    
    @property
    def side(self):
        """Order sides (0=Buy, 1=Sell)."""
    
    def total_size(self, **kwargs):
        """Total order size by column."""
    
    def total_fees(self, **kwargs):
        """Total fees paid by column."""
    
    def buy_orders(self, **kwargs):
        """Filter buy orders only."""
    
    def sell_orders(self, **kwargs):
        """Filter sell orders only."""

Trade Records

Comprehensive trade analysis with entry/exit matching and performance calculation.

class Trades(Records):
    """
    Trade records with entry/exit matching.
    
    Analyzes completed trades with detailed performance metrics,
    duration analysis, and P&L calculations.
    """
    
    @property
    def entry_idx(self):
        """Entry timestamp indices."""
    
    @property
    def exit_idx(self):
        """Exit timestamp indices."""
    
    @property
    def entry_price(self):
        """Trade entry prices."""
    
    @property
    def exit_price(self):
        """Trade exit prices."""
    
    @property
    def size(self):
        """Trade sizes."""
    
    @property
    def pnl(self):
        """Trade profit/loss amounts."""
    
    @property
    def return_pct(self):
        """Trade returns as percentages."""
    
    @property
    def duration(self):
        """Trade durations."""
    
    def winning_trades(self, **kwargs):
        """Filter winning trades."""
    
    def losing_trades(self, **kwargs):
        """Filter losing trades."""
    
    def expectancy(self, **kwargs):
        """Calculate trade expectancy."""
    
    def win_rate(self, **kwargs):
        """Calculate win rate percentage."""

class EntryTrades(Trades):
    """Entry-specific trade records for detailed entry analysis."""

class ExitTrades(Trades):
    """Exit-specific trade records for detailed exit analysis."""

Position Records

Position tracking with detailed exposure and holding period analysis.

class Positions(Records):
    """
    Position records tracking.
    
    Monitors position sizes, durations, and P&L for portfolio
    analysis and risk management.
    """
    
    @property
    def entry_idx(self):
        """Position entry timestamp indices."""
    
    @property
    def exit_idx(self):
        """Position exit timestamp indices."""
    
    @property
    def size(self):
        """Position sizes."""
    
    @property
    def duration(self):
        """Position durations."""
    
    @property
    def pnl(self):
        """Position profit/loss."""
    
    def long_positions(self, **kwargs):
        """Filter long positions."""
    
    def short_positions(self, **kwargs):
        """Filter short positions."""
    
    def avg_duration(self, **kwargs):
        """Average position duration."""

Drawdown Records

Drawdown period analysis with detailed recovery tracking and risk metrics.

class Drawdowns(Records):
    """
    Drawdown period analysis.
    
    Tracks drawdown periods, depths, and recovery times for
    comprehensive risk analysis and portfolio evaluation.
    """
    
    @property
    def start_idx(self):
        """Drawdown start indices."""
    
    @property
    def valley_idx(self):
        """Drawdown valley (lowest point) indices."""
    
    @property
    def end_idx(self):
        """Drawdown end indices."""
    
    @property
    def drawdown(self):
        """Drawdown percentages."""
    
    @property
    def duration(self):
        """Drawdown durations."""
    
    @property
    def recovery_duration(self):
        """Recovery durations."""
    
    def max_drawdown(self, **kwargs):
        """Maximum drawdown by column."""
    
    def avg_drawdown(self, **kwargs):
        """Average drawdown by column."""
    
    def recovery_factor(self, **kwargs):
        """Recovery factor calculation."""

Usage Examples

Basic Record Filtering

import vectorbt as vbt

# Get portfolio trades
portfolio = vbt.Portfolio.from_signals(price, entries, exits)
trades = portfolio.trades

# Filter winning trades
winning_trades = trades.winning_trades()
print(f"Win rate: {trades.win_rate():.2%}")

# Analyze trade durations
avg_duration = trades.duration.mean()
print(f"Average trade duration: {avg_duration}")

Order Analysis

# Analyze order execution
orders = portfolio.orders

# Calculate total trading costs
total_fees = orders.total_fees()
print(f"Total fees paid: ${total_fees:.2f}")

# Analyze buy vs sell orders
buy_orders = orders.buy_orders()
sell_orders = orders.sell_orders()

Drawdown Analysis

# Analyze drawdown periods
drawdowns = portfolio.drawdowns

# Find maximum drawdown
max_dd = drawdowns.max_drawdown()
print(f"Maximum drawdown: {max_dd:.2%}")

# Analyze recovery patterns
avg_recovery = drawdowns.recovery_duration.mean()
print(f"Average recovery time: {avg_recovery} periods")

Types

# Record field types
from vectorbt.records.enums import *

# Order record structure
Order = np.dtype([
    ('id', np.int_),
    ('col', np.int_),
    ('idx', np.int_),
    ('size', np.float_),
    ('price', np.float_),
    ('fees', np.float_),
    ('side', np.int_)
])

# Trade record structure  
Trade = np.dtype([
    ('id', np.int_),
    ('col', np.int_),
    ('entry_idx', np.int_),
    ('exit_idx', np.int_),
    ('entry_price', np.float_),
    ('exit_price', np.float_),
    ('size', np.float_),
    ('pnl', np.float_),
    ('return_pct', np.float_)
])

Install with Tessl CLI

npx tessl i tessl/pypi-vectorbt

docs

data-management.md

generic-analysis.md

index.md

indicators-signals.md

label-generation.md

portfolio-analysis.md

records-management.md

utilities-config.md

tile.json