Skip to main content

Options strategy backtesting library

Project description

opstrat_backtester

PyPI Version License: MIT

A modular Python library for backtesting options strategies using data from the Brazilian market.

opstrat_backtester provides a straightforward, event-driven engine to help you test your trading ideas without getting bogged down in data fetching and portfolio management boilerplate.


Core Features

  • Efficient Data Handling: Implements an intelligent local caching system using Parquet files. Data is fetched from the API only once, making subsequent backtests significantly faster.
  • Modular Architecture: Built with a DataSource abstraction, allowing for future integration of other data providers beyond the current Oplab implementation.
  • Event-Driven Engine: The backtesting engine processes each day sequentially, handling trades, market events (like expirations), and portfolio valuation in a clear and logical order.
  • Simple Strategy Interface: To create a new strategy, you only need to subclass the Strategy class and implement your logic in the generate_signals method.
  • Analytics Included: Comes with basic functions to plot profit-and-loss curves and calculate common performance statistics.

Prerequisites

IMPORTANT: This library is designed to work with the Oplab API. You must have a valid Oplab API access key with permission to retrieve historical data.


Installation

Install the package directly from PyPI:

pip install opstrat_backtester

To set up for development, clone the repository and install with the dev dependencies:

pip install -e .[dev]

How to Use

1. Set Your API Token

The backtester requires your Oplab API token to be set as an environment variable.

export OPLAB_ACCESS_TOKEN="your_token_here"

2. Define Your Strategy

Create a class that inherits from Strategy and implements your trading logic.

from opstrat_backtester.core.strategy import Strategy
import pandas as pd

class MyStrategy(Strategy):
    def generate_signals(self, date: pd.Timestamp, daily_options_data: pd.DataFrame, stock_history: pd.DataFrame, portfolio):
        # Your trading logic goes here.
        # This method should return a list of trade signals.
        # Example: [{'ticker': 'PETRA123', 'quantity': 10}]
        signals = []
        custom_indicators = {} # Optional dictionary for logging custom data
        return signals, custom_indicators

3. Run the Backtest

Instantiate the OplabDataSource, your strategy, and the Backtester, then run the simulation.

from opstrat_backtester.core.engine import Backtester
from opstrat_backtester.data_loader import OplabDataSource
from opstrat_backtester.analytics.plots import plot_pnl

# --- Configuration ---
SPOT_SYMBOL = "BOVA11"
START_DATE = "2023-01-01"
END_DATE = "2024-03-31"

# 1. Instantiate the Data Source
data_source = OplabDataSource()

# 2. Instantiate your Strategy
my_strategy = MyStrategy()

# 3. Set up and run the Backtester
backtester = Backtester(
    strategy=my_strategy,
    start_date=START_DATE,
    end_date=END_DATE,
    spot_symbol=SPOT_SYMBOL
)
backtester.set_data_source(data_source)

# 4. Get the results
daily_summary_df, trades_df = backtester.run()

# 5. Plot the performance
plot_pnl(daily_summary_df, title=f"{SPOT_SYMBOL} Strategy Performance")

For complete, runnable examples, please see the Jupyter notebooks provided in the repository, such as example_delta_hedging.ipynb and example_vol_trading.ipynb.


Architecture Overview

  • api_client.py: Handles all communication with the Oplab API.
  • cache_manager.py: Manages both in-memory and on-disk (Parquet) caching to minimize API calls.
  • data_loader.py: Orchestrates data fetching and caching, acting as the bridge between the API client and the backtesting engine.
  • core/engine.py: The main backtesting engine that drives the simulation.
  • core/strategy.py: Contains the abstract Strategy class that you must implement.
  • core/portfolio.py: Manages portfolio state, including cash, positions, and trade history.

Contributing

Pull requests and issues are welcome. If you'd like to contribute, please feel free to fork the repository and submit a pull request with your changes.


License

This project is licensed under the MIT License.

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

opstrat_backtester-0.1.1.tar.gz (23.7 kB view details)

Uploaded Source

Built Distribution

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

opstrat_backtester-0.1.1-py3-none-any.whl (22.8 kB view details)

Uploaded Python 3

File details

Details for the file opstrat_backtester-0.1.1.tar.gz.

File metadata

  • Download URL: opstrat_backtester-0.1.1.tar.gz
  • Upload date:
  • Size: 23.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.24

File hashes

Hashes for opstrat_backtester-0.1.1.tar.gz
Algorithm Hash digest
SHA256 85f1e075438249e446b359a717cc850b0bb0bd3990ef4219053c95ca00d9485c
MD5 c508047c695fa780b5b4ef4a21d32ab4
BLAKE2b-256 fa231285b6533407dfdcb1f79bbf7d85372095a735265fbf51aaf8d38f14a833

See more details on using hashes here.

File details

Details for the file opstrat_backtester-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for opstrat_backtester-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 558efd866a8fd8c9e35c2d71ff6642dd67511bc16bcf76b14e010d9572dceb08
MD5 7442390f23924e0b5439155ca897f2d0
BLAKE2b-256 c6eb851ac37529551b5fef13e320f2113788caf3a5a6cad07c80a80c6e3b84b9

See more details on using hashes here.

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