Skip to main content

Trading strategies crafting tools

Project description

from ptahlmud.core import Fluctuations

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 pathlib import Path

from ptahlmud.backtesting.models import Signal, Side, Action
from ptahlmud.backtesting.backtest import TradingParameters, process_signals
from ptahlmud.datastack import FluctuationsService, BinanceClient, FluctuationsSpecs

client = BinanceClient(binance_secret="", binance_key="")
service = FluctuationsService(client, savedir=Path("/data/fluctuations_data"))

specifications = FluctuationsSpecs(
    coin="BTC", currency="USDT",
    from_date=datetime(2023, 1, 1),
    to_date=datetime(2023, 2, 1),
)

# Fetch and load the historical market data
service.fetch(specifications)
fluctuations = service.request(specifications)

# 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 = TradingParameters(
    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
)

# Run the backtest
trades = process_signals(
    signals=signals,
    parameters=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.backtesting.models.signal import Signal, Side, Action


def moving_average_strategy(fluctuations: Fluctuations, fast_period: int, slow_period: int) -> list[Signal]:
    """Moving average crossover strategy."""
    # Calculate moving averages (simplified example)
    fast_ma = fluctuations.dataframe["close"].rolling(fast_period).mean()
    slow_ma = fluctuations.dataframe["close"].rolling(slow_period).mean()

    ma_crossover = (fast_ma < slow_ma) & (fast_ma.shift(1) > slow_ma.shift(1))
    crossover_df = fluctuations.dataframe[ma_crossover]

    signals: list[Signal] = []
    for _, row in crossover_df.iterrows():
        signals.append(Signal(
            date=row["close_time"],
            action=Action.ENTER,
            side=Side.LONG
        ))

    return signals


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

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.9.tar.gz (20.4 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.9-py3-none-any.whl (26.9 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for ptahlmud-0.0.9.tar.gz
Algorithm Hash digest
SHA256 78ec3cb7e0682f9711736098248fbf36388253d950fad6698ea279f28febdcf5
MD5 8cafd49475d8bf5719fe9a339e392509
BLAKE2b-256 013df64bac2f8bb43969fbf0aed3f8c875130612d75376d7e8cba80416e47cac

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for ptahlmud-0.0.9-py3-none-any.whl
Algorithm Hash digest
SHA256 b1efb6b7e1aacd37ae03d51af4c1fdb446c470d41225ced5063aac49f48d5f35
MD5 73114f70271a243cac2d91ff5b60a16d
BLAKE2b-256 4467025de337f14b39e1f7396bce55d3e89beb0805cd065dcd69e1e1383d7c44

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