| Name | mtbacktest JSON |
| Version |
0.0.4
JSON |
| download |
| home_page | None |
| Summary | A packaged designed for backtesting single and multi ticker strategies |
| upload_time | 2024-10-26 11:20:05 |
| maintainer | None |
| docs_url | None |
| author | None |
| requires_python | >=3.8 |
| license | None |
| keywords |
|
| VCS |
 |
| bugtrack_url |
|
| requirements |
No requirements were recorded.
|
| Travis-CI |
No Travis.
|
| coveralls test coverage |
No coveralls.
|
# Backtest
Custom backtest framework
To back test your strategy using this frame work we first define the strategy you want to run,
An example multi-ticker strategy (long short), the custom strategy class must contain a self.trader attribute for the framework to run
```python
class MultiTickerDummyStrat():
def __init__(self):
self.trader = Strategy() # A virtual trader that you can submit orders and contains information about the portfolio it manages, you MUST DEFINE THIS AS 'self.trader'
self.account = self.trader.account
def signal(dreturn):
"""
Define the signal such that if the current day return is greater than 2% we open long position,
and vice versa, this is performed on all tickers passed into the iter function, which runs, 1 iteration
of the algorithm
"""
if dreturn > 2:
return 1
if dreturn < -2:
return -1
return 0
self.signal_func= signal
def iter(self, data, ticker):
"""
You must define an iter() method that takes in data and ticker (only 1 ticker) for 1 iteration of algorithm on 1 ticker
"""
curr_signal = self.signal_func(data['dreturn_' + ticker])
units = (self.account.buying_power // 3)/data['close_' + ticker]
curr_portfolio = self.account.portfolio_snapshots.iloc[-1]['portfolio']
open_positions = [pos for pos in curr_portfolio.positions if pos.symbol == ticker and pos.status == 'open']
if curr_signal == 1:
'''
We long equity
'''
if len(open_positions) == 0:
self.trader.create_position(data['timestamp'], ticker, units, data['close_'+ticker])
elif curr_signal == -1:
'''
We short equity
'''
if len(open_positions) == 0:
self.trader.create_position(data['timestamp'], ticker, -units, data['close_'+ticker])
elif curr_signal == 0 and len(open_positions) > 0:
'''
We close position
'''
self.trader.close_position(data['timestamp'], ticker, data['close_'+ticker])
```
Then you can backtest the strategy like the following, if you choose to bring your own data
```python
from strategy import Strategy
from backtest import Backtest
from lib.preprocessing import df_to_dict, data_preprocess
import pandas as pd
import numpy as np
data = pd.read_json('test_data1.json')
data2 = pd.read_json('test_data2.json')
# Define your own custom features
data['dreturn'] = ((data['close'] - data['open'])/data['open']) * 100
data2['dreturn'] = ((data2['close'] - data2['open'])/data2['open']) * 100
data2 = data2.iloc[-100:]
data = data.iloc[-100:]
# standardise data for passing into the backtester
data = df_to_dict([data, data2], ['AAPL', 'TSLA']) # dataframe order should align with ticker list order
data = data_preprocess(data)
# Initiate backtest
bt = Backtest(MultiTickerDummyStrat, data, ['AAPL', 'TSLA'])
bt.run(verbose=1)
bt.plot()
```
<<<<<<< HEAD
=======
The library also supports data fetching utilities, you can fetch data for stocks traded on US exchanges and LSE as well as crypto, note that when requesting for crypto data you should add "-USD" as suffix, for example, "BTC-USD", "SOL-USD", are accepted tickers.
An example of usage of the data collection utility is,
```python
from data import Data
client = Data()
daily_data = client.get_daily_data(['AAPL', 'TSLA']) # for daily data
# The accepted intervals are 1m, 5m, 1h for intraday requests
intraday_data = client.get_intraday_data(['AAPL', 'TSLA'], interval='5m') # for intraday data
```
The data requested from the data module will be already standardised for parsing into the backtester, so no further processing is required, however, you will need to engineer your own feature if required, for future updates, we will implement a function to assist feature engineering.
>>>>>>> test
Raw data
{
"_id": null,
"home_page": null,
"name": "mtbacktest",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": null,
"author": null,
"author_email": "Jiajian He <2211054370abc@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/d0/da/c9f99cb950adfb478ebc04fd88f1da53a1f555c46cbb5fdc0b95d2a360d6/mtbacktest-0.0.4.tar.gz",
"platform": null,
"description": "# Backtest\nCustom backtest framework\n\nTo back test your strategy using this frame work we first define the strategy you want to run,\n\nAn example multi-ticker strategy (long short), the custom strategy class must contain a self.trader attribute for the framework to run\n\n```python\nclass MultiTickerDummyStrat():\n def __init__(self):\n self.trader = Strategy() # A virtual trader that you can submit orders and contains information about the portfolio it manages, you MUST DEFINE THIS AS 'self.trader'\n self.account = self.trader.account\n def signal(dreturn):\n \"\"\"\n Define the signal such that if the current day return is greater than 2% we open long position,\n and vice versa, this is performed on all tickers passed into the iter function, which runs, 1 iteration\n of the algorithm\n \"\"\"\n if dreturn > 2:\n return 1\n if dreturn < -2:\n return -1\n return 0\n self.signal_func= signal\n \n def iter(self, data, ticker):\n \"\"\"\n You must define an iter() method that takes in data and ticker (only 1 ticker) for 1 iteration of algorithm on 1 ticker\n \"\"\"\n curr_signal = self.signal_func(data['dreturn_' + ticker])\n units = (self.account.buying_power // 3)/data['close_' + ticker]\n curr_portfolio = self.account.portfolio_snapshots.iloc[-1]['portfolio']\n open_positions = [pos for pos in curr_portfolio.positions if pos.symbol == ticker and pos.status == 'open']\n if curr_signal == 1:\n '''\n We long equity\n '''\n if len(open_positions) == 0:\n self.trader.create_position(data['timestamp'], ticker, units, data['close_'+ticker])\n \n elif curr_signal == -1:\n '''\n We short equity\n '''\n if len(open_positions) == 0:\n self.trader.create_position(data['timestamp'], ticker, -units, data['close_'+ticker])\n\n elif curr_signal == 0 and len(open_positions) > 0:\n '''\n We close position\n '''\n self.trader.close_position(data['timestamp'], ticker, data['close_'+ticker])\n```\n\nThen you can backtest the strategy like the following, if you choose to bring your own data\n\n```python\nfrom strategy import Strategy\nfrom backtest import Backtest\nfrom lib.preprocessing import df_to_dict, data_preprocess\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_json('test_data1.json')\ndata2 = pd.read_json('test_data2.json')\n\n# Define your own custom features\ndata['dreturn'] = ((data['close'] - data['open'])/data['open']) * 100\ndata2['dreturn'] = ((data2['close'] - data2['open'])/data2['open']) * 100\ndata2 = data2.iloc[-100:]\ndata = data.iloc[-100:]\n\n# standardise data for passing into the backtester\ndata = df_to_dict([data, data2], ['AAPL', 'TSLA']) # dataframe order should align with ticker list order\ndata = data_preprocess(data)\n\n# Initiate backtest\nbt = Backtest(MultiTickerDummyStrat, data, ['AAPL', 'TSLA'])\nbt.run(verbose=1)\nbt.plot()\n```\n<<<<<<< HEAD\n=======\n\nThe library also supports data fetching utilities, you can fetch data for stocks traded on US exchanges and LSE as well as crypto, note that when requesting for crypto data you should add \"-USD\" as suffix, for example, \"BTC-USD\", \"SOL-USD\", are accepted tickers.\n\nAn example of usage of the data collection utility is,\n\n```python\nfrom data import Data\nclient = Data()\ndaily_data = client.get_daily_data(['AAPL', 'TSLA']) # for daily data\n# The accepted intervals are 1m, 5m, 1h for intraday requests\nintraday_data = client.get_intraday_data(['AAPL', 'TSLA'], interval='5m') # for intraday data\n```\n\nThe data requested from the data module will be already standardised for parsing into the backtester, so no further processing is required, however, you will need to engineer your own feature if required, for future updates, we will implement a function to assist feature engineering.\n>>>>>>> test\n",
"bugtrack_url": null,
"license": null,
"summary": "A packaged designed for backtesting single and multi ticker strategies",
"version": "0.0.4",
"project_urls": {
"Homepage": "https://github.com/jeffhe1/Backtest"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "e8f5b926dadc539ad00485a188b846456e2cebe7ebbdfc90cd4297c7ce98b797",
"md5": "f050bcfd59d602f72e257f9e82017288",
"sha256": "fa2c98be37667b419eb5fba126cc188d8b93639451bb47efeeee406205cfb65b"
},
"downloads": -1,
"filename": "mtbacktest-0.0.4-py3-none-any.whl",
"has_sig": false,
"md5_digest": "f050bcfd59d602f72e257f9e82017288",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 1616395,
"upload_time": "2024-10-26T11:19:57",
"upload_time_iso_8601": "2024-10-26T11:19:57.915085Z",
"url": "https://files.pythonhosted.org/packages/e8/f5/b926dadc539ad00485a188b846456e2cebe7ebbdfc90cd4297c7ce98b797/mtbacktest-0.0.4-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "d0dac9f99cb950adfb478ebc04fd88f1da53a1f555c46cbb5fdc0b95d2a360d6",
"md5": "82b0b04e3f95b84e96bebeb84c1be560",
"sha256": "0945748d1faae7143ebf53059a1ee419458f06a36ec9b58d32b3b498ee26b1ec"
},
"downloads": -1,
"filename": "mtbacktest-0.0.4.tar.gz",
"has_sig": false,
"md5_digest": "82b0b04e3f95b84e96bebeb84c1be560",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 1596619,
"upload_time": "2024-10-26T11:20:05",
"upload_time_iso_8601": "2024-10-26T11:20:05.816797Z",
"url": "https://files.pythonhosted.org/packages/d0/da/c9f99cb950adfb478ebc04fd88f1da53a1f555c46cbb5fdc0b95d2a360d6/mtbacktest-0.0.4.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-10-26 11:20:05",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "jeffhe1",
"github_project": "Backtest",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "mtbacktest"
}