Skip to main content

Library created for the m203 python project. It is adding new features to the library pybacktestchain

Project description

m203mylibrary

m203mylibrary is a Python package that extends the functionality of the pybacktestchain library by introducing commodity futures contracts. The library introduces new features like handling futures expirations, a universal backtest class and performance plotting.

What's New

Futures Expiration Logic

The library introduces a methodology for managing futures contracts by:

  • Calculating expiry dates for multiple commodity types, including energy, soft commodities, and metals.
  • Implementing automatic rollover logic when contracts near expiration.
  • Introducing distinct handling for energy commodities (e.g., Crude Oil, Natural Gas) and CBOT agricultural products (e.g., Soybean, Corn).
  • Adjusting expiry dates to ensure they align with business days and accounting for specific market conventions.

This ensures that backtests reflect real-world trading scenarios where contracts expire and roll over to the next available month. It is also a methodology that make it possible to deal with yahoo finance data which is free but not really extensive for commodities, hence building expiry dates from available data.

Universal Backtest Framework

The new UniversalBacktest class provides:

  • A unified interface for running backtests across stocks and commodities portofolios.
  • Customizable inputs for the trading universe, risk models, rebalancing flags, and time intervals.
  • Support for commodity-specific features (futures expiry handling).
  • An integrated performance tracking and plotting feature.

Portfolio Performance Visualization

Performance metrics are now with the UniversalBacktest class. This feature enables:

  • Visualization of portfolio value, cash balance, and holdings value over time.
  • A clearer understanding of how the strategy evolves during the backtest period.

Installation

$ pip install m203mylibrary

Usage

Universal Backtest

The UniversalBacktest class is the centerpiece of the library, offering an enhanced backtesting framework. Below is a detailed explanation of its inputs and functionality.

Input Parameters

  • initial_date (datetime): The start date of the backtest.
  • final_date (datetime): The end date of the backtest.
  • asset_class (str): Specify "stocks" or "commodities".
  • initial_cash (float, default=1,000,000): The initial capital for the backtest.
  • verbose (bool, default=True): Enables detailed logging of operations.
  • universe (list, optional): A list of tickers to include in the backtest. Defaults:
    • For stocks: ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'META', 'TSLA', 'NVDA', 'INTC', 'CSCO', 'NFLX'].
    • For commodities: ['CL=F', 'BZ=F', 'NG=F', 'HO=F', 'ZS=F', 'ZW=F', 'ZC=F', 'CC=F'].
  • rebalance_flag (type, optional): Rebalancing logic. Defaults:
    • EndOfMonth for stocks.
    • EndOfMonthOrExpiry for commodities.
  • risk_model (type, optional): Risk management logic. Defaults:
    • StopLoss for stocks.
    • CommodityStopLoss for commodities.
  • adj_close_column (str, optional): Column used for price adjustments (default: "Adj Close" for stocks, "Close" for commodities).
  • expiry_column (str, optional): Specific to commodities; specifies the column for futures expiry.

Example Usage

  1. Stock Backtest
from m203mylibrary.multi_asset_backtest import UniversalBacktest
from datetime import datetime

backtest = UniversalBacktest(
    initial_date=datetime(2020, 1, 1),
    final_date=datetime(2021, 1, 1),
    asset_class="stocks",
    initial_cash=500000,
    verbose=True
)

result_log = backtest.run_backtest()
  1. Commodity Backtest with Custom Universe
from m203mylibrary.multi_asset_backtest import UniversalBacktest
from datetime import datetime

backtest = UniversalBacktest(
    initial_date=datetime(2022, 1, 1),
    final_date=datetime(2024, 1, 1),
    asset_class="commodities",
    universe=["CL=F", "NG=F", "ZS=F"],  # Custom tickers for Crude Oil, Natural Gas, Soybeans
    initial_cash=1000000,
    verbose=True
)

result_log = backtest.run_backtest()

Futures Expiration Example

from m203mylibrary.commodities_data_module import get_futures_expiry

buy_date = "2024-12-15"
ticker = "CL=F"  # Crude Oil futures
expiry_date = get_futures_expiry(buy_date, ticker)

print(f"The expiry date for {ticker} futures purchased on {buy_date} is {expiry_date}.")

Performance Visualization

The UniversalBacktest class automatically calculates and plots performance metrics, including:

  • Portfolio Value: Total value of holdings and cash.
  • Cash: Remaining liquid capital.
# Example Backtest with Plotting
from m203mylibrary import UniversalBacktest
from datetime import datetime

backtest = UniversalBacktest(
    initial_date=datetime(2020, 1, 1),
    final_date=datetime(2021, 1, 1),
    asset_class="commodities",
    universe=["CL=F", "NG=F"],
    verbose=True
)

backtest.run_backtest()

After running the backtest, a performance plot will automatically be displayed, providing insights into the strategy's evolution over time.


Contributing

Interested in contributing? Check out the contributing guidelines. Please note that this project is released with a Code of Conduct. By contributing to this project, you agree to abide by its terms.

License

m203mylibrary was created by Mehmet Basagac. It is licensed under the terms of the MIT license.

Credits

m203mylibrary builds upon pybacktestchain and was developed using cookiecutter with the py-pkgs-cookiecutter template.

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

m203mylibrary-0.1.3.tar.gz (13.6 kB view details)

Uploaded Source

Built Distribution

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

m203mylibrary-0.1.3-py3-none-any.whl (14.6 kB view details)

Uploaded Python 3

File details

Details for the file m203mylibrary-0.1.3.tar.gz.

File metadata

  • Download URL: m203mylibrary-0.1.3.tar.gz
  • Upload date:
  • Size: 13.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.13.0 Darwin/22.6.0

File hashes

Hashes for m203mylibrary-0.1.3.tar.gz
Algorithm Hash digest
SHA256 a285db45aaf9079523839cb65db152293042d4a445fa20d838bb2b34b542ea97
MD5 863385003529307f7467cf1c4d4f5f25
BLAKE2b-256 1c682f889fc5205eaeb4a521fd0ba3b7a9aa8a68598a6d88f9092fe79bab693c

See more details on using hashes here.

File details

Details for the file m203mylibrary-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: m203mylibrary-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 14.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.13.0 Darwin/22.6.0

File hashes

Hashes for m203mylibrary-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 274e54ed5d13e6681a02326bf5c59edc9edfd2b1bd09c573138e9f6562590768
MD5 95c860b2674894b204c3cfd71f723ef7
BLAKE2b-256 9f4866d346c59f4191c998f38fd9d6cdb8c15605e8100863d811927199e7369e

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