cipher-bt


Namecipher-bt JSON
Version 0.6.8 PyPI version JSON
download
home_pageNone
SummaryCipher - Trading Strategy Backtesting Framework.
upload_time2025-08-17 13:19:11
maintainerNone
docs_urlNone
authorNone
requires_python<3.13,>=3.9
licenseNone
keywords backtest colab crypto framework quant strategy trading
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Cipher - Trading Strategy Backtesting Framework

![Tests](https://github.com/nanvel/cipher-bt/actions/workflows/tests.yaml/badge.svg)
[![PyPI version](https://badge.fury.io/py/cipher-bt.svg)](https://badge.fury.io/py/cipher-bt)
[![Python Versions](https://img.shields.io/pypi/pyversions/cipher-bt.svg)](https://pypi.python.org/pypi/cipher-bt/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

![cipher](https://github.com/nanvel/cipher-bt/raw/master/docs/cipher.jpeg)

- [Usage](#usage)  
- [Development](#development)
- [Disclaimer](#disclaimer)

Documentation: https://cipher.nanvel.com

**Features:**

- Well-structured, intuitive, and easily extensible design
- Support for multiple concurrent trading sessions
- Sophisticated exit strategies including trailing take profits
- Multi-source data integration (exchanges, symbols, timeframes)
- Clean separation between signal generation and handling
- Simple execution - just run `python my_strategy.py`
- Compatibility with [Google Colab](https://colab.research.google.com/)
- Built-in visualization with [finplot](https://github.com/highfestiva/finplot) and [mplfinance](https://github.com/matplotlib/mplfinance) plotters

## Usage

Set up a new strategies workspace and create your first strategy:
```shell
mkdir strategies
cd strategies
uv init
uv add 'cipher-bt[finplot,talib]'

uv run cipher init
uv run cipher new my_strategy
uv run python my_strategy.py
```

Complete EMA crossover strategy example:
```python
import numpy as np
import talib

from cipher import Cipher, Session, Strategy


class EmaCrossoverStrategy(Strategy):
    def __init__(self, fast_ema_length=9, slow_ema_length=21, trend_ema_length=200):
        self.fast_ema_length = fast_ema_length
        self.slow_ema_length = slow_ema_length
        self.trend_ema_length = trend_ema_length

    def compose(self):
        df = self.datas.df
        df["fast_ema"] = talib.EMA(df["close"], timeperiod=self.fast_ema_length)
        df["slow_ema"] = talib.EMA(df["close"], timeperiod=self.slow_ema_length)
        df["trend_ema"] = talib.EMA(df["close"], timeperiod=self.trend_ema_length)

        df["difference"] = df["fast_ema"] - df["slow_ema"]

        # Signal columns must be boolean type
        df["entry"] = np.sign(df["difference"].shift(1)) != np.sign(df["difference"])

        df["max_6"] = df["high"].rolling(window=6).max()
        df["min_6"] = df["low"].rolling(window=6).min()

        return df

    def on_entry(self, row: dict, session: Session):
        if row["difference"] > 0 and row["close"] > row["trend_ema"]:
            # Open a new long position
            session.position += "0.01"
            session.stop_loss = row["min_6"]
            session.take_profit = row["close"] + 1.5 * (row["close"] - row["min_6"])

        elif row["difference"] < 0 and row["close"] < row["trend_ema"]:
            # Open a new short position
            session.position -= "0.01"
            session.stop_loss = row["max_6"]
            session.take_profit = row["close"] - 1.5 * (row["max_6"] - row["close"])

    # def on_<signal>(self, row: dict, session: Session) -> None:
    #     """Custom signal handler called for each active session.
    #     Adjust or close positions and modify brackets here."""
    #     # session.position = 1
    #     # session.position = base(1)  # equivalent to the above
    #     # session.position = '1'  # int, str, float are converted to Decimal
    #     # session.position = quote(100)  # position worth 100 quote asset
    #     # session.position += 1  # add to the position
    #     # session.position -= Decimal('1.25')  # reduce position by 1.25
    #     # session.position += percent(50)  # add 50% more to position
    #     # session.position *= 1.5  # equivalent to the above
    #     pass
    #
    # def on_take_profit(self, row: dict, session: Session) -> None:
    #     """Called when take profit is hit. Default action closes the position.
    #     Modify position and brackets here to continue the session."""
    #     session.position = 0
    #
    # def on_stop_loss(self, row: dict, session: Session) -> None:
    #     """Called when stop loss is hit. Default action closes the position.
    #     Modify position and brackets here to continue the session."""
    #     session.position = 0
    #
    # def on_stop(self, row: dict, session: Session) -> None:
    #     """Called for each active session when dataframe ends.
    #     Close open sessions here, otherwise they will be ignored."""
    #     session.position = 0


def main():
    cipher = Cipher()
    cipher.add_source("binance_spot_ohlc", symbol="BTCUSDT", interval="1h")
    cipher.set_strategy(EmaCrossoverStrategy())
    cipher.run(start_ts="2025-01-01", stop_ts="2025-04-01")
    cipher.set_commission("0.00075")
    print(cipher.sessions)
    print(cipher.stats)
    cipher.plot()


if __name__ == "__main__":
    main()
```

![ema_crossover_plot](https://github.com/nanvel/cipher-bt/raw/master/docs/plotter.png)

## Development

```shell
brew install uv
uv sync --all-extras
source .venv/bin/activate

pytest tests
cipher --help
```

## Disclaimer

This software is for educational purposes only. Do not risk money you cannot afford to lose.
USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "cipher-bt",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<3.13,>=3.9",
    "maintainer_email": null,
    "keywords": "backtest, colab, crypto, framework, quant, strategy, trading",
    "author": null,
    "author_email": "Oleksandr Polieno <oleksandr@nanvel.com>",
    "download_url": "https://files.pythonhosted.org/packages/e2/bd/3bf2aea8af6ca15af5c1b7938d863e0ab264d53aed4a32b19165bd8a85c8/cipher_bt-0.6.8.tar.gz",
    "platform": null,
    "description": "# Cipher - Trading Strategy Backtesting Framework\n\n![Tests](https://github.com/nanvel/cipher-bt/actions/workflows/tests.yaml/badge.svg)\n[![PyPI version](https://badge.fury.io/py/cipher-bt.svg)](https://badge.fury.io/py/cipher-bt)\n[![Python Versions](https://img.shields.io/pypi/pyversions/cipher-bt.svg)](https://pypi.python.org/pypi/cipher-bt/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n![cipher](https://github.com/nanvel/cipher-bt/raw/master/docs/cipher.jpeg)\n\n- [Usage](#usage)  \n- [Development](#development)\n- [Disclaimer](#disclaimer)\n\nDocumentation: https://cipher.nanvel.com\n\n**Features:**\n\n- Well-structured, intuitive, and easily extensible design\n- Support for multiple concurrent trading sessions\n- Sophisticated exit strategies including trailing take profits\n- Multi-source data integration (exchanges, symbols, timeframes)\n- Clean separation between signal generation and handling\n- Simple execution - just run `python my_strategy.py`\n- Compatibility with [Google Colab](https://colab.research.google.com/)\n- Built-in visualization with [finplot](https://github.com/highfestiva/finplot) and [mplfinance](https://github.com/matplotlib/mplfinance) plotters\n\n## Usage\n\nSet up a new strategies workspace and create your first strategy:\n```shell\nmkdir strategies\ncd strategies\nuv init\nuv add 'cipher-bt[finplot,talib]'\n\nuv run cipher init\nuv run cipher new my_strategy\nuv run python my_strategy.py\n```\n\nComplete EMA crossover strategy example:\n```python\nimport numpy as np\nimport talib\n\nfrom cipher import Cipher, Session, Strategy\n\n\nclass EmaCrossoverStrategy(Strategy):\n    def __init__(self, fast_ema_length=9, slow_ema_length=21, trend_ema_length=200):\n        self.fast_ema_length = fast_ema_length\n        self.slow_ema_length = slow_ema_length\n        self.trend_ema_length = trend_ema_length\n\n    def compose(self):\n        df = self.datas.df\n        df[\"fast_ema\"] = talib.EMA(df[\"close\"], timeperiod=self.fast_ema_length)\n        df[\"slow_ema\"] = talib.EMA(df[\"close\"], timeperiod=self.slow_ema_length)\n        df[\"trend_ema\"] = talib.EMA(df[\"close\"], timeperiod=self.trend_ema_length)\n\n        df[\"difference\"] = df[\"fast_ema\"] - df[\"slow_ema\"]\n\n        # Signal columns must be boolean type\n        df[\"entry\"] = np.sign(df[\"difference\"].shift(1)) != np.sign(df[\"difference\"])\n\n        df[\"max_6\"] = df[\"high\"].rolling(window=6).max()\n        df[\"min_6\"] = df[\"low\"].rolling(window=6).min()\n\n        return df\n\n    def on_entry(self, row: dict, session: Session):\n        if row[\"difference\"] > 0 and row[\"close\"] > row[\"trend_ema\"]:\n            # Open a new long position\n            session.position += \"0.01\"\n            session.stop_loss = row[\"min_6\"]\n            session.take_profit = row[\"close\"] + 1.5 * (row[\"close\"] - row[\"min_6\"])\n\n        elif row[\"difference\"] < 0 and row[\"close\"] < row[\"trend_ema\"]:\n            # Open a new short position\n            session.position -= \"0.01\"\n            session.stop_loss = row[\"max_6\"]\n            session.take_profit = row[\"close\"] - 1.5 * (row[\"max_6\"] - row[\"close\"])\n\n    # def on_<signal>(self, row: dict, session: Session) -> None:\n    #     \"\"\"Custom signal handler called for each active session.\n    #     Adjust or close positions and modify brackets here.\"\"\"\n    #     # session.position = 1\n    #     # session.position = base(1)  # equivalent to the above\n    #     # session.position = '1'  # int, str, float are converted to Decimal\n    #     # session.position = quote(100)  # position worth 100 quote asset\n    #     # session.position += 1  # add to the position\n    #     # session.position -= Decimal('1.25')  # reduce position by 1.25\n    #     # session.position += percent(50)  # add 50% more to position\n    #     # session.position *= 1.5  # equivalent to the above\n    #     pass\n    #\n    # def on_take_profit(self, row: dict, session: Session) -> None:\n    #     \"\"\"Called when take profit is hit. Default action closes the position.\n    #     Modify position and brackets here to continue the session.\"\"\"\n    #     session.position = 0\n    #\n    # def on_stop_loss(self, row: dict, session: Session) -> None:\n    #     \"\"\"Called when stop loss is hit. Default action closes the position.\n    #     Modify position and brackets here to continue the session.\"\"\"\n    #     session.position = 0\n    #\n    # def on_stop(self, row: dict, session: Session) -> None:\n    #     \"\"\"Called for each active session when dataframe ends.\n    #     Close open sessions here, otherwise they will be ignored.\"\"\"\n    #     session.position = 0\n\n\ndef main():\n    cipher = Cipher()\n    cipher.add_source(\"binance_spot_ohlc\", symbol=\"BTCUSDT\", interval=\"1h\")\n    cipher.set_strategy(EmaCrossoverStrategy())\n    cipher.run(start_ts=\"2025-01-01\", stop_ts=\"2025-04-01\")\n    cipher.set_commission(\"0.00075\")\n    print(cipher.sessions)\n    print(cipher.stats)\n    cipher.plot()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n![ema_crossover_plot](https://github.com/nanvel/cipher-bt/raw/master/docs/plotter.png)\n\n## Development\n\n```shell\nbrew install uv\nuv sync --all-extras\nsource .venv/bin/activate\n\npytest tests\ncipher --help\n```\n\n## Disclaimer\n\nThis software is for educational purposes only. Do not risk money you cannot afford to lose.\nUSE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Cipher - Trading Strategy Backtesting Framework.",
    "version": "0.6.8",
    "project_urls": {
        "Homepage": "https://cipher.nanvel.com/",
        "Repository": "https://github.com/nanvel/cipher-bt"
    },
    "split_keywords": [
        "backtest",
        " colab",
        " crypto",
        " framework",
        " quant",
        " strategy",
        " trading"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "e1f66064e80bdcd78036a15ad8087f9ea34b4e952f115ec88a52f80c4be0e272",
                "md5": "249776cdd6cef1ba26aca6f1fe978038",
                "sha256": "ca1313060c593a3fb79a70296873c71edbf056e3c558e054953902c421c5b75d"
            },
            "downloads": -1,
            "filename": "cipher_bt-0.6.8-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "249776cdd6cef1ba26aca6f1fe978038",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<3.13,>=3.9",
            "size": 39980,
            "upload_time": "2025-08-17T13:19:10",
            "upload_time_iso_8601": "2025-08-17T13:19:10.320840Z",
            "url": "https://files.pythonhosted.org/packages/e1/f6/6064e80bdcd78036a15ad8087f9ea34b4e952f115ec88a52f80c4be0e272/cipher_bt-0.6.8-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "e2bd3bf2aea8af6ca15af5c1b7938d863e0ab264d53aed4a32b19165bd8a85c8",
                "md5": "65193e9181cfab70729f18090291a26c",
                "sha256": "461e16c188f870cdb64ec6ec57cc8a52d2237ed0c1deb5cee36c0fbc56a61128"
            },
            "downloads": -1,
            "filename": "cipher_bt-0.6.8.tar.gz",
            "has_sig": false,
            "md5_digest": "65193e9181cfab70729f18090291a26c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<3.13,>=3.9",
            "size": 22054,
            "upload_time": "2025-08-17T13:19:11",
            "upload_time_iso_8601": "2025-08-17T13:19:11.886302Z",
            "url": "https://files.pythonhosted.org/packages/e2/bd/3bf2aea8af6ca15af5c1b7938d863e0ab264d53aed4a32b19165bd8a85c8/cipher_bt-0.6.8.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-17 13:19:11",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "nanvel",
    "github_project": "cipher-bt",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "cipher-bt"
}
        
Elapsed time: 1.71184s