Skip to main content

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.

Metadata

Release files for m203mylibrary 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for m203mylibrary 0.1.3
File Size Uploaded Provenance Actions
m203mylibrary-0.1.3.tar.gz 13.6 kB Without provenance Details for m203mylibrary-0.1.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for m203mylibrary 0.1.3
File Interpreter ABI Platform Actions
m203mylibrary-0.1.3-py3-none-any.whl Python 3 none any Details for m203mylibrary-0.1.3-py3-none-any.whl

Total release size: 28.2 kB

Release files / m203mylibrary-0.1.3.tar.gz

Download URL m203mylibrary-0.1.3.tar.gz
Size 13.6 kB
Tags Source
SHA-256 checksum
How to use checksums
a285db45aaf9079523839cb65db152293042d4a445fa20d838bb2b34b542ea97
BLAKE2b-256 checksum
How to use checksums
1c682f889fc5205eaeb4a521fd0ba3b7a9aa8a68598a6d88f9092fe79bab693c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.4 CPython/3.13.0 Darwin/22.6.0

Release files / m203mylibrary-0.1.3-py3-none-any.whl

Download URL m203mylibrary-0.1.3-py3-none-any.whl
Size 14.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
274e54ed5d13e6681a02326bf5c59edc9edfd2b1bd09c573138e9f6562590768
BLAKE2b-256 checksum
How to use checksums
9f4866d346c59f4191c998f38fd9d6cdb8c15605e8100863d811927199e7369e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.4 CPython/3.13.0 Darwin/22.6.0

Security for m203mylibrary 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page