vectorbt


Namevectorbt JSON
Version 0.27.0 PyPI version JSON
download
home_pagehttps://github.com/polakowo/vectorbt
SummaryPython library for backtesting and analyzing trading strategies at scale
upload_time2024-12-18 13:07:50
maintainerNone
docs_urlNone
authorOleg Polakow
requires_python>=3.6
licenseApache 2.0 with Commons Clause
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            <div align="center">
    <a href="https://vectorbt.pro/" alt="https://vectorbt.pro/">
        <img src="https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/logo/header-pro.svg" />
    </a>
</div>
<div align="center">
    <a href="https://vectorbt.dev/" alt="https://vectorbt.dev/">
        <img src="https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/logo/header.svg" />
    </a>
</div>
<br>
<p align="center">
    <a href="https://pepy.tech/project/vectorbt" alt="Downloads">
        <img src="https://pepy.tech/badge/vectorbt" />
    </a>
    <a href="https://pypi.org/project/vectorbt" alt="PyPi">
        <img src="https://img.shields.io/pypi/v/vectorbt?color=blueviolet" />
    </a>
    <a href="https://github.com/polakowo/vectorbt/blob/master/LICENSE.md" alt="License">
	<img src="https://img.shields.io/badge/license-Fair%20Code-yellow" />
    </a>
    <a href="https://codecov.io/gh/polakowo/vectorbt" alt="codecov">
        <img src="https://codecov.io/gh/polakowo/vectorbt/branch/master/graph/badge.svg?token=YTLNAI7PS3" />
    </a>
    <a href="https://vectorbt.dev/" alt="Website">
        <img src="https://img.shields.io/website?url=https://vectorbt.dev/" />
    </a>
    <a href="https://mybinder.org/v2/gh/polakowo/vectorbt/HEAD?urlpath=lab" alt="Binder">
        <img src="https://img.shields.io/badge/launch-binder-d6604a" />
    </a>
    <a href="https://gitter.im/vectorbt/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" alt="Join the chat at https://gitter.im/vectorbt/community">
        <img src="https://badges.gitter.im/vectorbt.svg" />
    </a>
</p>
<p align="center">
    <a href="https://pypi.org/project/vectorbt" alt="Python Versions">
        <img src="https://img.shields.io/pypi/pyversions/vectorbt.svg?logo=python&logoColor=white" />
    </a>
</p>

## :sparkles: Usage

vectorbt allows you to easily backtest strategies with a couple of lines of Python code.

* Here is how much profit we would have made if we invested $100 into Bitcoin in 2014:

```python
import vectorbt as vbt

price = vbt.YFData.download('BTC-USD').get('Close')

pf = vbt.Portfolio.from_holding(price, init_cash=100)
pf.total_profit()
```

```plaintext
8961.008555963961
```

* Buy whenever 10-day SMA crosses above 50-day SMA and sell when opposite:

```python
fast_ma = vbt.MA.run(price, 10)
slow_ma = vbt.MA.run(price, 50)
entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)

pf = vbt.Portfolio.from_signals(price, entries, exits, init_cash=100)
pf.total_profit()
```

```plaintext
16423.251963801864
```

* Generate 1,000 strategies with random signals and test them on BTC and ETH:

```python
import numpy as np

symbols = ["BTC-USD", "ETH-USD"]
price = vbt.YFData.download(symbols, missing_index='drop').get('Close')

n = np.random.randint(10, 101, size=1000).tolist()
pf = vbt.Portfolio.from_random_signals(price, n=n, init_cash=100, seed=42)

mean_expectancy = pf.trades.expectancy().groupby(['randnx_n', 'symbol']).mean()
fig = mean_expectancy.unstack().vbt.scatterplot(xaxis_title='randnx_n', yaxis_title='mean_expectancy')
fig.show()
```

![rand_scatter.svg](https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/images/usage_rand_scatter.svg)

* For fans of hyperparameter optimization: here is a snippet for testing 10,000 window combinations of a 
dual SMA crossover strategy on BTC, USD, and LTC:

```python
symbols = ["BTC-USD", "ETH-USD", "LTC-USD"]
price = vbt.YFData.download(symbols, missing_index='drop').get('Close')

windows = np.arange(2, 101)
fast_ma, slow_ma = vbt.MA.run_combs(price, window=windows, r=2, short_names=['fast', 'slow'])
entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)

pf_kwargs = dict(size=np.inf, fees=0.001, freq='1D')
pf = vbt.Portfolio.from_signals(price, entries, exits, **pf_kwargs)

fig = pf.total_return().vbt.heatmap(
    x_level='fast_window', y_level='slow_window', slider_level='symbol', symmetric=True,
    trace_kwargs=dict(colorbar=dict(title='Total return', tickformat='%')))
fig.show()
```

<img width="650" src="https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/images/usage_dmac_heatmap.gif">

Digging into each strategy configuration is as simple as indexing with pandas:

```python
pf[(10, 20, 'ETH-USD')].stats()
```

```plaintext
Start                          2015-08-07 00:00:00+00:00
End                            2021-08-01 00:00:00+00:00
Period                                2183 days 00:00:00
Start Value                                        100.0
End Value                                  620402.791485
Total Return [%]                           620302.791485
Benchmark Return [%]                        92987.961948
Max Gross Exposure [%]                             100.0
Total Fees Paid                             10991.676981
Max Drawdown [%]                               70.734951
Max Drawdown Duration                  760 days 00:00:00
Total Trades                                          54
Total Closed Trades                                   53
Total Open Trades                                      1
Open Trade PnL                              67287.940601
Win Rate [%]                                   52.830189
Best Trade [%]                               1075.803607
Worst Trade [%]                               -29.593414
Avg Winning Trade [%]                          95.695343
Avg Losing Trade [%]                          -11.890246
Avg Winning Trade Duration    35 days 23:08:34.285714286
Avg Losing Trade Duration                8 days 00:00:00
Profit Factor                                   2.651143
Expectancy                                   10434.24247
Sharpe Ratio                                    2.041211
Calmar Ratio                                      4.6747
Omega Ratio                                     1.547013
Sortino Ratio                                   3.519894
Name: (10, 20, ETH-USD), dtype: object
```

The same for plotting:

```python
pf[(10, 20, 'ETH-USD')].plot().show()
```

![dmac_portfolio.svg](https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/images/usage_dmac_portfolio.svg)

It's not all about backtesting - vectorbt can be used to facilitate financial data analysis and visualization.

* Let's generate a GIF that animates the %B and bandwidth of Bollinger Bands for different symbols:

```python
symbols = ["BTC-USD", "ETH-USD", "ADA-USD"]
price = vbt.YFData.download(symbols, period='6mo', missing_index='drop').get('Close')
bbands = vbt.BBANDS.run(price)

def plot(index, bbands):
    bbands = bbands.loc[index]
    fig = vbt.make_subplots(
        rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.15,
        subplot_titles=('%B', 'Bandwidth'))
    fig.update_layout(template='vbt_dark', showlegend=False, width=750, height=400)
    bbands.percent_b.vbt.ts_heatmap(
        trace_kwargs=dict(zmin=0, zmid=0.5, zmax=1, colorscale='Spectral', colorbar=dict(
            y=(fig.layout.yaxis.domain[0] + fig.layout.yaxis.domain[1]) / 2, len=0.5
        )), add_trace_kwargs=dict(row=1, col=1), fig=fig)
    bbands.bandwidth.vbt.ts_heatmap(
        trace_kwargs=dict(colorbar=dict(
            y=(fig.layout.yaxis2.domain[0] + fig.layout.yaxis2.domain[1]) / 2, len=0.5
        )), add_trace_kwargs=dict(row=2, col=1), fig=fig)
    return fig

vbt.save_animation('bbands.gif', bbands.wrapper.index, plot, bbands, delta=90, step=3, fps=3)
```

```plaintext
100%|██████████| 31/31 [00:21<00:00,  1.21it/s]
```

<img width="750" src="https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/images/usage_bbands.gif">

And this is just the tip of the iceberg of what's possible. Check out the [website](https://vectorbt.dev/) to learn more.

## Installation

```sh
pip install -U vectorbt
```

To also install optional dependencies:

```sh
pip install -U "vectorbt[full]"
```

## Colab Notebook

[Google Colaboratory](https://colab.research.google.com/drive/1ibqyrf6LPFlzRb6mkPpl3hxqL6ryNBXI?usp=sharing)

## License

This work is [fair-code](http://faircode.io/) distributed under [Apache 2.0 with Commons Clause](https://github.com/polakowo/vectorbt/blob/master/LICENSE.md) license. 
The source code is open and everyone (individuals and organizations) can use it for free. 
However, it is not allowed to sell products and services that are mostly just this software.

If you have any questions about this or want to apply for a license exception, please [contact the author](mailto:olegpolakow@gmail.com).

Installing optional dependencies may be subject to a more restrictive license.

## Star History

[![Star History Chart](https://api.star-history.com/svg?repos=polakowo/vectorbt&type=Timeline)](https://star-history.com/#polakowo/vectorbt&Timeline)

## Disclaimer

This software is for educational purposes only. Do not risk money which you are afraid 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": "https://github.com/polakowo/vectorbt",
    "name": "vectorbt",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": null,
    "keywords": null,
    "author": "Oleg Polakow",
    "author_email": "olegpolakow@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/1d/ab/bd7ef81409ed1f75967f78c68ed5a08d3824f1a8b770feaa4a68d848e3d7/vectorbt-0.27.0.tar.gz",
    "platform": null,
    "description": "<div align=\"center\">\n    <a href=\"https://vectorbt.pro/\" alt=\"https://vectorbt.pro/\">\n        <img src=\"https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/logo/header-pro.svg\" />\n    </a>\n</div>\n<div align=\"center\">\n    <a href=\"https://vectorbt.dev/\" alt=\"https://vectorbt.dev/\">\n        <img src=\"https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/logo/header.svg\" />\n    </a>\n</div>\n<br>\n<p align=\"center\">\n    <a href=\"https://pepy.tech/project/vectorbt\" alt=\"Downloads\">\n        <img src=\"https://pepy.tech/badge/vectorbt\" />\n    </a>\n    <a href=\"https://pypi.org/project/vectorbt\" alt=\"PyPi\">\n        <img src=\"https://img.shields.io/pypi/v/vectorbt?color=blueviolet\" />\n    </a>\n    <a href=\"https://github.com/polakowo/vectorbt/blob/master/LICENSE.md\" alt=\"License\">\n\t<img src=\"https://img.shields.io/badge/license-Fair%20Code-yellow\" />\n    </a>\n    <a href=\"https://codecov.io/gh/polakowo/vectorbt\" alt=\"codecov\">\n        <img src=\"https://codecov.io/gh/polakowo/vectorbt/branch/master/graph/badge.svg?token=YTLNAI7PS3\" />\n    </a>\n    <a href=\"https://vectorbt.dev/\" alt=\"Website\">\n        <img src=\"https://img.shields.io/website?url=https://vectorbt.dev/\" />\n    </a>\n    <a href=\"https://mybinder.org/v2/gh/polakowo/vectorbt/HEAD?urlpath=lab\" alt=\"Binder\">\n        <img src=\"https://img.shields.io/badge/launch-binder-d6604a\" />\n    </a>\n    <a href=\"https://gitter.im/vectorbt/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge\" alt=\"Join the chat at https://gitter.im/vectorbt/community\">\n        <img src=\"https://badges.gitter.im/vectorbt.svg\" />\n    </a>\n</p>\n<p align=\"center\">\n    <a href=\"https://pypi.org/project/vectorbt\" alt=\"Python Versions\">\n        <img src=\"https://img.shields.io/pypi/pyversions/vectorbt.svg?logo=python&logoColor=white\" />\n    </a>\n</p>\n\n## :sparkles: Usage\n\nvectorbt allows you to easily backtest strategies with a couple of lines of Python code.\n\n* Here is how much profit we would have made if we invested $100 into Bitcoin in 2014:\n\n```python\nimport vectorbt as vbt\n\nprice = vbt.YFData.download('BTC-USD').get('Close')\n\npf = vbt.Portfolio.from_holding(price, init_cash=100)\npf.total_profit()\n```\n\n```plaintext\n8961.008555963961\n```\n\n* Buy whenever 10-day SMA crosses above 50-day SMA and sell when opposite:\n\n```python\nfast_ma = vbt.MA.run(price, 10)\nslow_ma = vbt.MA.run(price, 50)\nentries = fast_ma.ma_crossed_above(slow_ma)\nexits = fast_ma.ma_crossed_below(slow_ma)\n\npf = vbt.Portfolio.from_signals(price, entries, exits, init_cash=100)\npf.total_profit()\n```\n\n```plaintext\n16423.251963801864\n```\n\n* Generate 1,000 strategies with random signals and test them on BTC and ETH:\n\n```python\nimport numpy as np\n\nsymbols = [\"BTC-USD\", \"ETH-USD\"]\nprice = vbt.YFData.download(symbols, missing_index='drop').get('Close')\n\nn = np.random.randint(10, 101, size=1000).tolist()\npf = vbt.Portfolio.from_random_signals(price, n=n, init_cash=100, seed=42)\n\nmean_expectancy = pf.trades.expectancy().groupby(['randnx_n', 'symbol']).mean()\nfig = mean_expectancy.unstack().vbt.scatterplot(xaxis_title='randnx_n', yaxis_title='mean_expectancy')\nfig.show()\n```\n\n![rand_scatter.svg](https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/images/usage_rand_scatter.svg)\n\n* For fans of hyperparameter optimization: here is a snippet for testing 10,000 window combinations of a \ndual SMA crossover strategy on BTC, USD, and LTC:\n\n```python\nsymbols = [\"BTC-USD\", \"ETH-USD\", \"LTC-USD\"]\nprice = vbt.YFData.download(symbols, missing_index='drop').get('Close')\n\nwindows = np.arange(2, 101)\nfast_ma, slow_ma = vbt.MA.run_combs(price, window=windows, r=2, short_names=['fast', 'slow'])\nentries = fast_ma.ma_crossed_above(slow_ma)\nexits = fast_ma.ma_crossed_below(slow_ma)\n\npf_kwargs = dict(size=np.inf, fees=0.001, freq='1D')\npf = vbt.Portfolio.from_signals(price, entries, exits, **pf_kwargs)\n\nfig = pf.total_return().vbt.heatmap(\n    x_level='fast_window', y_level='slow_window', slider_level='symbol', symmetric=True,\n    trace_kwargs=dict(colorbar=dict(title='Total return', tickformat='%')))\nfig.show()\n```\n\n<img width=\"650\" src=\"https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/images/usage_dmac_heatmap.gif\">\n\nDigging into each strategy configuration is as simple as indexing with pandas:\n\n```python\npf[(10, 20, 'ETH-USD')].stats()\n```\n\n```plaintext\nStart                          2015-08-07 00:00:00+00:00\nEnd                            2021-08-01 00:00:00+00:00\nPeriod                                2183 days 00:00:00\nStart Value                                        100.0\nEnd Value                                  620402.791485\nTotal Return [%]                           620302.791485\nBenchmark Return [%]                        92987.961948\nMax Gross Exposure [%]                             100.0\nTotal Fees Paid                             10991.676981\nMax Drawdown [%]                               70.734951\nMax Drawdown Duration                  760 days 00:00:00\nTotal Trades                                          54\nTotal Closed Trades                                   53\nTotal Open Trades                                      1\nOpen Trade PnL                              67287.940601\nWin Rate [%]                                   52.830189\nBest Trade [%]                               1075.803607\nWorst Trade [%]                               -29.593414\nAvg Winning Trade [%]                          95.695343\nAvg Losing Trade [%]                          -11.890246\nAvg Winning Trade Duration    35 days 23:08:34.285714286\nAvg Losing Trade Duration                8 days 00:00:00\nProfit Factor                                   2.651143\nExpectancy                                   10434.24247\nSharpe Ratio                                    2.041211\nCalmar Ratio                                      4.6747\nOmega Ratio                                     1.547013\nSortino Ratio                                   3.519894\nName: (10, 20, ETH-USD), dtype: object\n```\n\nThe same for plotting:\n\n```python\npf[(10, 20, 'ETH-USD')].plot().show()\n```\n\n![dmac_portfolio.svg](https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/images/usage_dmac_portfolio.svg)\n\nIt's not all about backtesting - vectorbt can be used to facilitate financial data analysis and visualization.\n\n* Let's generate a GIF that animates the %B and bandwidth of Bollinger Bands for different symbols:\n\n```python\nsymbols = [\"BTC-USD\", \"ETH-USD\", \"ADA-USD\"]\nprice = vbt.YFData.download(symbols, period='6mo', missing_index='drop').get('Close')\nbbands = vbt.BBANDS.run(price)\n\ndef plot(index, bbands):\n    bbands = bbands.loc[index]\n    fig = vbt.make_subplots(\n        rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.15,\n        subplot_titles=('%B', 'Bandwidth'))\n    fig.update_layout(template='vbt_dark', showlegend=False, width=750, height=400)\n    bbands.percent_b.vbt.ts_heatmap(\n        trace_kwargs=dict(zmin=0, zmid=0.5, zmax=1, colorscale='Spectral', colorbar=dict(\n            y=(fig.layout.yaxis.domain[0] + fig.layout.yaxis.domain[1]) / 2, len=0.5\n        )), add_trace_kwargs=dict(row=1, col=1), fig=fig)\n    bbands.bandwidth.vbt.ts_heatmap(\n        trace_kwargs=dict(colorbar=dict(\n            y=(fig.layout.yaxis2.domain[0] + fig.layout.yaxis2.domain[1]) / 2, len=0.5\n        )), add_trace_kwargs=dict(row=2, col=1), fig=fig)\n    return fig\n\nvbt.save_animation('bbands.gif', bbands.wrapper.index, plot, bbands, delta=90, step=3, fps=3)\n```\n\n```plaintext\n100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 31/31 [00:21<00:00,  1.21it/s]\n```\n\n<img width=\"750\" src=\"https://raw.githubusercontent.com/polakowo/vectorbt/master/docs/docs/assets/images/usage_bbands.gif\">\n\nAnd this is just the tip of the iceberg of what's possible. Check out the [website](https://vectorbt.dev/) to learn more.\n\n## Installation\n\n```sh\npip install -U vectorbt\n```\n\nTo also install optional dependencies:\n\n```sh\npip install -U \"vectorbt[full]\"\n```\n\n## Colab Notebook\n\n[Google Colaboratory](https://colab.research.google.com/drive/1ibqyrf6LPFlzRb6mkPpl3hxqL6ryNBXI?usp=sharing)\n\n## License\n\nThis work is [fair-code](http://faircode.io/) distributed under [Apache 2.0 with Commons Clause](https://github.com/polakowo/vectorbt/blob/master/LICENSE.md) license. \nThe source code is open and everyone (individuals and organizations) can use it for free. \nHowever, it is not allowed to sell products and services that are mostly just this software.\n\nIf you have any questions about this or want to apply for a license exception, please [contact the author](mailto:olegpolakow@gmail.com).\n\nInstalling optional dependencies may be subject to a more restrictive license.\n\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=polakowo/vectorbt&type=Timeline)](https://star-history.com/#polakowo/vectorbt&Timeline)\n\n## Disclaimer\n\nThis software is for educational purposes only. Do not risk money which you are afraid 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": "Apache 2.0 with Commons Clause",
    "summary": "Python library for backtesting and analyzing trading strategies at scale",
    "version": "0.27.0",
    "project_urls": {
        "Homepage": "https://github.com/polakowo/vectorbt"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "fc632241de9a81ed34dbfa764cab13d845e9bda53eeef606207486cd49e4de5c",
                "md5": "c26de8fe02120fd377c1c4f14af8f55b",
                "sha256": "6a22fa88edd295ad5b85c8f47339183ffaacd3824874a85740fff3bb65ef016e"
            },
            "downloads": -1,
            "filename": "vectorbt-0.27.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c26de8fe02120fd377c1c4f14af8f55b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 527437,
            "upload_time": "2024-12-18T13:07:43",
            "upload_time_iso_8601": "2024-12-18T13:07:43.841883Z",
            "url": "https://files.pythonhosted.org/packages/fc/63/2241de9a81ed34dbfa764cab13d845e9bda53eeef606207486cd49e4de5c/vectorbt-0.27.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1dabbd7ef81409ed1f75967f78c68ed5a08d3824f1a8b770feaa4a68d848e3d7",
                "md5": "29c69fa1b06116682730721e8dd779eb",
                "sha256": "e46d0a8d53bda8936009cdd202a61cc5bd8f6769bf862dafeb190b6303d00804"
            },
            "downloads": -1,
            "filename": "vectorbt-0.27.0.tar.gz",
            "has_sig": false,
            "md5_digest": "29c69fa1b06116682730721e8dd779eb",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 486430,
            "upload_time": "2024-12-18T13:07:50",
            "upload_time_iso_8601": "2024-12-18T13:07:50.873003Z",
            "url": "https://files.pythonhosted.org/packages/1d/ab/bd7ef81409ed1f75967f78c68ed5a08d3824f1a8b770feaa4a68d848e3d7/vectorbt-0.27.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-18 13:07:50",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "polakowo",
    "github_project": "vectorbt",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "vectorbt"
}
        
Elapsed time: 0.39884s