# TIBacktester
> `tibacktester` is originally a fork of Pybroker,
> however our goal is to use the utils and libraries from pybroker to build a new backtesting engine,
> to support these main unique features besides the good existing features in pybroker (numba acceleration, machine learning strategy support, etc):
- Option Backtesting.
Simulate and evaluate option trading strategies with historical data to analyze performance, risk, and return under different market conditions.
- Multi-Asset & Portfolio Backtesting.
Support strategies that leverage correlations between different assets, enabling portfolio-level backtesting, multi-asset strategies, and pair trading approaches.
- Strategy Optimization.
Optimize strategies using well-known libraries and algorithms from machine learning and AI, such as grid search, genetic algorithms, or reinforcement learning techniques.
- Built-in Strategies Library.
Access a collection of pre-built, common trading strategies to test and deploy out of the box, making it easier to get started and benchmark performance.
## Why we create this new backtesting library?
Pybroker is a great backtesting library, it is fast and with machine learning strategy support by default,
it has built-in mechanism to avoid forward looking bias, however, it has some limitations too.
1. When I tried to use pybroker to test a pair trading strategy,
using a common pair as an example, trade between KO and PEP based on their price ratio,
In current pybroker design, when I trade KO, I cannot get information about PEP in the same execution function,
If I provide a PEP dataframe globally, it will lose the advantage of pybroker's forward looking bias avoidance mechanism,
2. No Options Backtesting
Similar to many existing libraries, PyBroker does not support options backtesting. This restricts its usefulness for traders and researchers focused on derivative strategies
## Roadmap of TiBacktester
- [ ] New backtesting engine (to support multi asset backtesting)
- [ ] Charting library integration (to visualize the backtesting result)
- [ ] Market Value
- [ ] Drawdown
- [ ] Trades, Long/Short Positions
- [ ] Sharpe Ratio line
- [ ] Consider using EagerPy to improve the performance
- [ ] Strategy parameters optimization
- [ ] Built-in strategies library
- [ ] Option backtesting
- [ ] Fetch options data
- [ ] Option pricing models
- [ ] Option Greeks calculation
- [ ] Backtest Option Only Strategies
- [ ] Backtest Stock + Option Strategies, such as covered call, protective put, etc.
> The idea is to use existing utils and functions from pybroker as much as possible to build this new backtesting engine.
> We haven't created the documentation yet, so please refer to the examples below or pybroker's documentation for now: https://pybroker.readthedocs.io/en/latest/, new documentation will be created when it is ready.
## Algorithmic Trading in Python with Machine Learning
Are you looking to enhance your trading strategies with the power of Python and
machine learning? Then you need to check out **TIBacktester**! This Python framework
is designed for developing algorithmic trading strategies, with a focus on
strategies that use machine learning. With TIBacktester, you can easily create and
fine-tune trading rules, build powerful models, and gain valuable insights into
your strategy’s performance.
## Key Features
- A super-fast backtesting engine built in [NumPy](https://numpy.org/) and accelerated with [Numba](https://numba.pydata.org/).
- The ability to create and execute trading rules and models across multiple instruments with ease.
- Access to historical data from [Alpaca](https://alpaca.markets/), [Yahoo Finance](https://finance.yahoo.com/), [AKShare](https://github.com/akfamily/akshare), or from [your own data provider](https://www.TIBacktester.com/en/latest/notebooks/7.%20Creating%20a%20Custom%20Data%20Source.html).
- The option to train and backtest models using [Walkforward Analysis](https://www.TIBacktester.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis), which simulates how the strategy would perform during actual trading.
- More reliable trading metrics that use randomized [bootstrapping](https://en.wikipedia.org/wiki/Bootstrapping_(statistics)) to provide more accurate results.
- Caching of downloaded data, indicators, and models to speed up your development process.
- Parallelized computations that enable faster performance.
With TIBacktester, you'll have all the tools you need to create winning trading
strategies backed by data and machine learning. Start using TIBacktester today and
take your trading to the next level!
## Installation
TIBacktester supports Python 3.9+ on Windows, Mac, and Linux. You can install
TIBacktester using `pip`:
```bash
pip install -U tibacktester
```
Or you can clone the Git repository with:
```bash
git clone https://github.com/Tradeinsight-info/TIBacktester
```
## A Quick Example
Get a glimpse of what backtesting with TIBacktester looks like with these code
snippets:
**Rule-based Strategy**:
```python
from tibacktester import Strategy, YFinance, highest
def exec_fn(ctx):
# Get the rolling 10 day high.
high_10d = ctx.indicator('high_10d')
# Buy on a new 10 day high.
if not ctx.long_pos() and high_10d[-1] > high_10d[-2]:
ctx.buy_shares = 100
# Hold the position for 5 days.
ctx.hold_bars = 5
# Set a stop loss of 2%.
ctx.stop_loss_pct = 2
strategy = Strategy(YFinance(), start_date='1/1/2022', end_date='7/1/2022')
strategy.add_execution(
exec_fn, ['AAPL', 'MSFT'], indicators=highest('high_10d', 'close', period=10))
# Run the backtest after 20 days have passed.
result = strategy.backtest(warmup=20)
```
**Model-based Strategy**:
```python
from tibacktester import Alpaca, Strategy, model
def train_fn(train_data, test_data, ticker):
# Train the model using indicators stored in train_data.
...
return trained_model
# Register the model and its training function with TIBacktester.
my_model = model('my_model', train_fn, indicators=[...])
def exec_fn(ctx):
preds = ctx.preds('my_model')
# Open a long position given my_model's latest prediction.
if not ctx.long_pos() and preds[-1] > buy_threshold:
ctx.buy_shares = 100
# Close the long position given my_model's latest prediction.
elif ctx.long_pos() and preds[-1] < sell_threshold:
ctx.sell_all_shares()
alpaca = Alpaca(api_key=..., api_secret=...)
strategy = Strategy(alpaca, start_date='1/1/2022', end_date='7/1/2022')
strategy.add_execution(exec_fn, ['AAPL', 'MSFT'], models=my_model)
# Run Walkforward Analysis on 1 minute data using 5 windows with 50/50 train/test data.
result = strategy.walkforward(timeframe='1m', windows=5, train_size=0.5)
```
Raw data
{
"_id": null,
"home_page": null,
"name": "tibacktester",
"maintainer": null,
"docs_url": null,
"requires_python": "<3.13,>=3.10",
"maintainer_email": null,
"keywords": "Algorithm Trading, Backtesting",
"author": "tim-hub",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/64/10/485a2f39353ce329b9276d0d31bfbf5fe99383f777bf6c05e9cff4ad0b60/tibacktester-25.9.5.post1209.tar.gz",
"platform": null,
"description": "# TIBacktester\n> `tibacktester` is originally a fork of Pybroker, \n> however our goal is to use the utils and libraries from pybroker to build a new backtesting engine,\n> to support these main unique features besides the good existing features in pybroker (numba acceleration, machine learning strategy support, etc):\n\n- Option Backtesting. \nSimulate and evaluate option trading strategies with historical data to analyze performance, risk, and return under different market conditions.\n\n- Multi-Asset & Portfolio Backtesting. \nSupport strategies that leverage correlations between different assets, enabling portfolio-level backtesting, multi-asset strategies, and pair trading approaches.\n\n- Strategy Optimization. \nOptimize strategies using well-known libraries and algorithms from machine learning and AI, such as grid search, genetic algorithms, or reinforcement learning techniques.\n\n- Built-in Strategies Library. \nAccess a collection of pre-built, common trading strategies to test and deploy out of the box, making it easier to get started and benchmark performance.\n\n\n## Why we create this new backtesting library?\n\nPybroker is a great backtesting library, it is fast and with machine learning strategy support by default, \nit has built-in mechanism to avoid forward looking bias, however, it has some limitations too.\n\n1. When I tried to use pybroker to test a pair trading strategy, \nusing a common pair as an example, trade between KO and PEP based on their price ratio,\nIn current pybroker design, when I trade KO, I cannot get information about PEP in the same execution function,\nIf I provide a PEP dataframe globally, it will lose the advantage of pybroker's forward looking bias avoidance mechanism,\n2. No Options Backtesting\nSimilar to many existing libraries, PyBroker does not support options backtesting. This restricts its usefulness for traders and researchers focused on derivative strategies\n\n\n## Roadmap of TiBacktester\n\n\n- [ ] New backtesting engine (to support multi asset backtesting)\n- [ ] Charting library integration (to visualize the backtesting result)\n - [ ] Market Value\n - [ ] Drawdown\n - [ ] Trades, Long/Short Positions\n - [ ] Sharpe Ratio line\n- [ ] Consider using EagerPy to improve the performance\n- [ ] Strategy parameters optimization \n- [ ] Built-in strategies library\n- [ ] Option backtesting\n - [ ] Fetch options data \n - [ ] Option pricing models\n - [ ] Option Greeks calculation\n - [ ] Backtest Option Only Strategies\n - [ ] Backtest Stock + Option Strategies, such as covered call, protective put, etc.\n\n> The idea is to use existing utils and functions from pybroker as much as possible to build this new backtesting engine.\n\n\n\n> We haven't created the documentation yet, so please refer to the examples below or pybroker's documentation for now: https://pybroker.readthedocs.io/en/latest/, new documentation will be created when it is ready.\n\n\n## Algorithmic Trading in Python with Machine Learning\n\nAre you looking to enhance your trading strategies with the power of Python and\nmachine learning? Then you need to check out **TIBacktester**! This Python framework\nis designed for developing algorithmic trading strategies, with a focus on\nstrategies that use machine learning. With TIBacktester, you can easily create and\nfine-tune trading rules, build powerful models, and gain valuable insights into\nyour strategy\u2019s performance.\n\n\n\n## Key Features\n\n- A super-fast backtesting engine built in [NumPy](https://numpy.org/) and accelerated with [Numba](https://numba.pydata.org/).\n- The ability to create and execute trading rules and models across multiple instruments with ease.\n- Access to historical data from [Alpaca](https://alpaca.markets/), [Yahoo Finance](https://finance.yahoo.com/), [AKShare](https://github.com/akfamily/akshare), or from [your own data provider](https://www.TIBacktester.com/en/latest/notebooks/7.%20Creating%20a%20Custom%20Data%20Source.html).\n- The option to train and backtest models using [Walkforward Analysis](https://www.TIBacktester.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis), which simulates how the strategy would perform during actual trading.\n- More reliable trading metrics that use randomized [bootstrapping](https://en.wikipedia.org/wiki/Bootstrapping_(statistics)) to provide more accurate results.\n- Caching of downloaded data, indicators, and models to speed up your development process.\n- Parallelized computations that enable faster performance.\n\nWith TIBacktester, you'll have all the tools you need to create winning trading\nstrategies backed by data and machine learning. Start using TIBacktester today and\ntake your trading to the next level!\n\n## Installation\n\nTIBacktester supports Python 3.9+ on Windows, Mac, and Linux. You can install\nTIBacktester using `pip`:\n\n```bash\n pip install -U tibacktester\n```\n\nOr you can clone the Git repository with:\n\n```bash\n git clone https://github.com/Tradeinsight-info/TIBacktester\n```\n\n## A Quick Example\n\nGet a glimpse of what backtesting with TIBacktester looks like with these code\nsnippets:\n\n**Rule-based Strategy**:\n\n```python\nfrom tibacktester import Strategy, YFinance, highest\n\ndef exec_fn(ctx):\n # Get the rolling 10 day high.\n high_10d = ctx.indicator('high_10d')\n # Buy on a new 10 day high.\n if not ctx.long_pos() and high_10d[-1] > high_10d[-2]:\n ctx.buy_shares = 100\n # Hold the position for 5 days.\n ctx.hold_bars = 5\n # Set a stop loss of 2%.\n ctx.stop_loss_pct = 2\n\nstrategy = Strategy(YFinance(), start_date='1/1/2022', end_date='7/1/2022')\nstrategy.add_execution(\n exec_fn, ['AAPL', 'MSFT'], indicators=highest('high_10d', 'close', period=10))\n# Run the backtest after 20 days have passed.\nresult = strategy.backtest(warmup=20)\n```\n\n**Model-based Strategy**:\n\n```python\nfrom tibacktester import Alpaca, Strategy, model\n\ndef train_fn(train_data, test_data, ticker):\n # Train the model using indicators stored in train_data.\n ...\n return trained_model\n\n# Register the model and its training function with TIBacktester.\nmy_model = model('my_model', train_fn, indicators=[...])\n\ndef exec_fn(ctx):\n preds = ctx.preds('my_model')\n # Open a long position given my_model's latest prediction.\n if not ctx.long_pos() and preds[-1] > buy_threshold:\n ctx.buy_shares = 100\n # Close the long position given my_model's latest prediction.\n elif ctx.long_pos() and preds[-1] < sell_threshold:\n ctx.sell_all_shares()\n\nalpaca = Alpaca(api_key=..., api_secret=...)\nstrategy = Strategy(alpaca, start_date='1/1/2022', end_date='7/1/2022')\nstrategy.add_execution(exec_fn, ['AAPL', 'MSFT'], models=my_model)\n# Run Walkforward Analysis on 1 minute data using 5 windows with 50/50 train/test data.\nresult = strategy.walkforward(timeframe='1m', windows=5, train_size=0.5)\n```\n\n\n",
"bugtrack_url": null,
"license": "Apache",
"summary": "TI-Backtester, yet another quantitative trading library.",
"version": "25.9.5.post1209",
"project_urls": {
"homepage": "https://github.com/TradeInsight-Info/tibacktester"
},
"split_keywords": [
"algorithm trading",
" backtesting"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "6410485a2f39353ce329b9276d0d31bfbf5fe99383f777bf6c05e9cff4ad0b60",
"md5": "731bd61d43cd9b076d17eb24563afeb4",
"sha256": "45ef8a6448644717d6c3809291d5ec9cc2345678247a26d58964ef05b399f86c"
},
"downloads": -1,
"filename": "tibacktester-25.9.5.post1209.tar.gz",
"has_sig": false,
"md5_digest": "731bd61d43cd9b076d17eb24563afeb4",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<3.13,>=3.10",
"size": 123625,
"upload_time": "2025-09-05T00:15:42",
"upload_time_iso_8601": "2025-09-05T00:15:42.665507Z",
"url": "https://files.pythonhosted.org/packages/64/10/485a2f39353ce329b9276d0d31bfbf5fe99383f777bf6c05e9cff4ad0b60/tibacktester-25.9.5.post1209.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-09-05 00:15:42",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "TradeInsight-Info",
"github_project": "tibacktester",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "tibacktester"
}