Skip to main content

Trading strategies crafting tools

Project description

ptahlmud

Python library for crafting and backtesting trading strategies. Ptahlmud helps you design, test, and evaluate algorithmic trading strategies using historical market data.

Features

This project is still under construction and features may be added or reworked.

  • Signal-based trading: Define entry and exit points with customizable signals
  • Portfolio simulation: Track your strategy's performance over time
  • Risk management: Configure position sizing, take-profit, and stop-loss parameters
  • Backtesting engine: Test strategies against historical market data

Installation

pip install ptahlmud

Quick Start

Here's a simple example of defining trading signals and running a backtest:

from datetime import datetime

from ptahlmud.backtesting.backtest import RiskConfig, process_signals
from ptahlmud.entities.fluctuations import Fluctuations
from ptahlmud.types.signal import Signal, Side, Action

# Define trading signals
signals = [
    Signal(date=datetime(2023, 1, 1), side=Side.LONG, action=Action.ENTER),
    Signal(date=datetime(2023, 1, 15), side=Side.LONG, action=Action.EXIT),
    Signal(date=datetime(2023, 2, 1), side=Side.SHORT, action=Action.ENTER),
    Signal(date=datetime(2023, 2, 15), side=Side.SHORT, action=Action.EXIT),
]

# Configure risk management
risk_config = RiskConfig(
    size=0.1,          # Use 10% of available capital per trade
    take_profit=0.05,  # Take profit at 5% price increase
    stop_loss=0.03,    # Cut losses at 3% price decrease
)

# Load market data (you'll need to implement this for your data source)
fluctuations: Fluctuations = load_your_market_data(...)

# Run the backtest
trades = process_signals(
    signals=signals,
    risk_config=risk_config,
    fluctuations=fluctuations,
)

# Analyze results
print(f"Number of trades : {len(trades)}")
print(f"Total profit : {sum([trade.total_profit for trade in trades])}")
print(f"Win rate : {sum([1 for trade in trades if trade.total_profit > 0]) / len(trades)}")

Advanced Usage

Creating a Custom Strategy

You can define custom trading strategies by creating signals based on technical indicators or other market conditions:

from ptahlmud.types.signal import Signal, Side, Action

def moving_average_strategy(fluctuations, fast_period: int, slow_period: int) -> list[Signal]:
    """Simple moving average crossover strategy."""
    signals: list[Signal] = []

    # Calculate moving averages (simplified example)
    fast_ma = calculate_moving_average(fluctuations, fast_period)
    slow_ma = calculate_moving_average(fluctuations, slow_period)

    # Generate signals on crossovers
    for index, candle in enumerate(fluctuations.candles):
        # fast ma crossed above slow ma
        if fast_ma[index-1] < slow_ma[index-1] and fast_ma[index] > slow_ma[index]:
            signals.append(Signal(
                date=candle.close_time,
                side=Side.LONG,
                action=Action.ENTER
            ))

        # slow ma crossed bellow slow ma
        if fast_ma[index-1] > slow_ma[index-1] and fast_ma[index] < slow_ma[index]:
            signals.append(Signal(
                date=candle.close_time,
                side=Side.LONG,
                action=Action.EXIT
            ))

    return signals

signals = moving_average_strategy(market_date, fast_period=10, slow_period=30)
trades = process_signals(
    signals=signals,
    fluctuations=market_date,
    risk_config=risk_config,
)

Development

It is recommended to work in a virtual environment, you can install pyenv with python >= 3.11.

pyenv install 3.12.5
pyenv virtualenv 3.12.5 ptahlmud
pyenv activate ptahlmud
# Clone the repository
git clone https://github.com/yourusername/ptahlmud.git
cd ptahlmud

Setup environment

make setup

Run tests

make test

Run code quality checks

make check

Contributing

Contributions are welcome! You can open an issue, submit a pull-request or simply chat with me. I'm always pleased to discuss design, performance or technical stuff.

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

ptahlmud-0.0.4.tar.gz (14.3 kB view details)

Uploaded Source

Built Distribution

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

ptahlmud-0.0.4-py3-none-any.whl (18.6 kB view details)

Uploaded Python 3

File details

Details for the file ptahlmud-0.0.4.tar.gz.

File metadata

  • Download URL: ptahlmud-0.0.4.tar.gz
  • Upload date:
  • Size: 14.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.12.11 Linux/6.11.0-1015-azure

File hashes

Hashes for ptahlmud-0.0.4.tar.gz
Algorithm Hash digest
SHA256 cbe9d275302845135813e3411f5de2c1b881fc29a48005de9c1b98358e9433c6
MD5 a6472065b735210e9507352bb62e1b3c
BLAKE2b-256 a01bd284b9f7e830710df8751c81246fc2de78355a7d628425cce2ec6d05eefd

See more details on using hashes here.

File details

Details for the file ptahlmud-0.0.4-py3-none-any.whl.

File metadata

  • Download URL: ptahlmud-0.0.4-py3-none-any.whl
  • Upload date:
  • Size: 18.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.12.11 Linux/6.11.0-1015-azure

File hashes

Hashes for ptahlmud-0.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 4289a974a767cdb40fad8a3060a5e9d51347d57bd9f06300afa6b66d6c397f66
MD5 b49afb9e4e83b7d129f92ca73290ed04
BLAKE2b-256 a0dc2ba8df3b42d701873797b97cb7bbcf22d34e8176372d1a24d3e9d043b997

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