bt - flexible backtesting for Python

Related tags

Finance bt
Overview

http://pmorissette.github.io/bt/_static/logo.png

bt - Flexible Backtesting for Python

bt is currently in alpha stage - if you find a bug, please submit an issue.

Read the docs here: http://pmorissette.github.io/bt.

What is bt?

bt is a flexible backtesting framework for Python used to test quantitative trading strategies. Backtesting is the process of testing a strategy over a given data set. This framework allows you to easily create strategies that mix and match different Algos. It aims to foster the creation of easily testable, re-usable and flexible blocks of strategy logic to facilitate the rapid development of complex trading strategies.

The goal: to save quants from re-inventing the wheel and let them focus on the important part of the job - strategy development.

bt is coded in Python and joins a vibrant and rich ecosystem for data analysis. Numerous libraries exist for machine learning, signal processing and statistics and can be leveraged to avoid re-inventing the wheel - something that happens all too often when using other languages that don't have the same wealth of high-quality, open-source projects.

bt is built atop ffn - a financial function library for Python. Check it out!

Features

  • Tree Structure
    The tree structure facilitates the construction and composition of complex algorithmic trading strategies that are modular and re-usable. Furthermore, each tree Node has its own price index that can be used by Algos to determine a Node's allocation.
  • Algorithm Stacks
    Algos and AlgoStacks are another core feature that facilitate the creation of modular and re-usable strategy logic. Due to their modularity, these logic blocks are also easier to test - an important step in building robust financial solutions.
  • Charting and Reporting
    bt also provides many useful charting functions that help visualize backtest results. We also plan to add more charts, tables and report formats in the future, such as automatically generated PDF reports.
  • Detailed Statistics
    Furthermore, bt calculates a bunch of stats relating to a backtest and offers a quick way to compare these various statistics across many different backtests via Results' display methods.

Roadmap

Future development efforts will focus on:

  • Speed
    Due to the flexible nature of bt, a trade-off had to be made between usability and performance. Usability will always be the priority, but we do wish to enhance the performance as much as possible.
  • Algos
    We will also be developing more algorithms as time goes on. We also encourage anyone to contribute their own algos as well.
  • Charting and Reporting
    This is another area we wish to constantly improve on as reporting is an important aspect of the job. Charting and reporting also facilitate finding bugs in strategy logic.

Installing bt

The easiest way to install bt is from the Python Package Index using pip or easy_insatll:

$ pip install bt

Since bt has many dependencies, we strongly recommend installing the Anaconda Scientific Python Distribution, especially on Windows. This distribution comes with many of the required packages pre-installed, including pip. Once Anaconda is installed, the above command should complete the installation.

bt should be compatible with Python 2.7 and Python 3 thanks to the contributions made by fellow users.

Recommended Setup

We believe the best environment to develop with bt is the IPython Notebook. From their homepage, the IPython Notebook is:

"[...] a web-based interactive computational environment where you can combine code execution, text, mathematics, plots and rich media into a single document [...]"

This environment allows you to plot your charts in-line and also allows you to easily add surrounding text with Markdown. You can easily create Notebooks that you can share with colleagues and you can also save them as PDFs. If you are not yet convinced, head over to their website.

Special Thanks

A special thanks to the following contributors for their involvement with the project:

License

MIT

Comments
  • Problem with bt.Backtest

    Problem with bt.Backtest

    Code: import bt

    data = bt.get('spy, agg', start='2010-01-01')

    s = bt.Strategy('s1', [bt.algos.RunMonthly(), bt.algos.SelectAll(), bt.algos.WeighEqually(), bt.algos.Rebalance()])

    test = bt.Backtest(s, data) res = bt.run(test)

    AttributeError Traceback (most recent call last) in () 8 bt.algos.Rebalance()]) 9 ---> 10 test = bt.Backtest(s, data) 11 res = bt.run(test)

    C:\Users****\Anaconda\lib\site-packages\bt\backtest.pyc in init(self, strategy, data, name, initial_capital, commissions, integer_positions) 120 integer_positions=True): 121 --> 122 if data.columns.duplicated().any(): 123 cols = data.columns[data.columns.duplicated().tolist()].tolist() 124 raise Exception(

    AttributeError: 'Index' object has no attribute 'duplicated'

    opened by nyobna 20
  • The example `SMA Crossover Strategy` failed

    The example `SMA Crossover Strategy` failed

    The example SMA Crossover Strategy in the document failed, and the error log is below:

    AttributeError: 'Series' object has no attribute 'items'
    

    I Think this is because the WeighTarget does not assign an dict to target.temp['weights'], so I just repacle target.temp['weights'] = w.dropna() with {w.index[i]:w.values[i] for i in range(len(w.index))} maybe there will be a better way.

    opened by bigtan 15
  • ImportError: No module named 'core'

    ImportError: No module named 'core'

    Hi, I'm a newbie to python, but I'm really interested in using your bt project for backtesting. I tried to follow the instructions --> install Anaconda for Mac (I used the 64bit version, Python 3.4). Everything installs fine and I can use Anaconda's python dist via terminal.

    Then, I try to import bt but I get this error:

    import bt Traceback (most recent call last): File "", line 1, in File "//anaconda/lib/python3.4/site-packages/bt/init.py", line 1, in import core ImportError: No module named 'core'

    What is the core module? I can't find it.

    Thanks!

    opened by starkrampf 13
  • test_strategybase_tree_rebalance_level2 failed

    test_strategybase_tree_rebalance_level2 failed

    When I run this test, This function test_strategybase_tree_rebalance_level2 failed because of the nan value of c1.weight.

    BTW, I port bt and ffn to python3 and run the test with nose, so maybe the port is not so perfect which lead to this bug.

    opened by bigtan 13
  • Simplification of long short strategy like in SIT R

    Simplification of long short strategy like in SIT R

    I have used systemic investor toolbox (SIT) package in R and its very good for backtesting. In that package creating signal for long, short or long-short strategy is very easy.

    #long only strategy
    signal<-ifelse(RSI3 < 30 & CCI20 > -290 & CCI20 < -100 & DEMA10c > -40 & DEMA10c < -20,1,NA)
    
    #short only strategy
    signal<-ifelse(RSI3 >30 & CCI20 > -290 & CCI20 > -100 & DEMA10c < -40 & DEMA10c > -20,-1,NA)
    
    #long and short strategy
    signal<-ifelse(RSI3 < 30 & CCI20 > -290 & CCI20 < -100 & DEMA10c > -40 & DEMA10c < -20,1,-1)
    
    

    and then pass the signal to a backtest function

    data$weight[] = NA
    data$weight[] = signal
    models$result = bt.run.share(data, clean.signal=T, trade.summary = TRUE)
    

    It would be easier if bt also has similar simplified functions.

    opened by ghost 12
  • Cannot allocate capital to 0 because price is 0 as of 2020-06-25 00:00:00

    Cannot allocate capital to 0 because price is 0 as of 2020-06-25 00:00:00

    Hi Phillippe, First of all thanks for creating a great package such as BT. I am running into some small hiatus here. Everything seems okay, and I think the data is in Dataframe and it could be shown in a graph. But when I am trying to run Backtest I get an exception message as follow: "

    Exception: Cannot allocate capital to 0 because price is 0 as of 2020-06-25 00:00:00`

    "

    any help would be highly appreciated.

    Thanks.

    `

    Construct the Signal and plotting it

    EMA_short = talib.EMA(price_data['tsla'], timeperiod=10).to_frame() EMA_long = talib.EMA(price_data['tsla'], timeperiod=40).to_frame()

    signal = EMA_long.copy() signal[EMA_long.isnull()] = 0

    signal[EMA_short > EMA_long] = 1 signal[EMA_short < EMA_long] = -1

    #Plot the signal, price and MAs combined_df = bt.merge(signal, price_data, EMA_short, EMA_long) combined_df.columns = ['Signal', 'Price', 'EMA_short', 'EMA_long']

    combined_df.plot(secondary_y=['Signal'])`

    image

    the plot looks okay but I am unable to use bt.run

    `

    Backtest

    #Define the strategy bt_strategy = bt.Strategy('EMA_crossover', [bt.algos.WeighTarget(signal), bt.algos.Rebalance()])

    #Create the backtest and run it bt_backtest = bt.Backtest(bt_strategy, price_data) bt_result = bt.run(bt_backtest)

    #Plot the backtest result bt_result.plot(title='Backtest result') `

    `

    Return Error


    Exception Traceback (most recent call last) in 6 #Create the backtest and run it 7 bt_backtest = bt.Backtest(bt_strategy, price_data) ----> 8 bt_result = bt.run(bt_backtest) 9 10 #Plot the backtest result

    ~/opt/anaconda3/lib/python3.8/site-packages/bt/backtest.py in run(*backtests) 26 # run each backtest 27 for bkt in backtests: ---> 28 bkt.run() 29 30 return Result(*backtests)

    ~/opt/anaconda3/lib/python3.8/site-packages/bt/backtest.py in run(self) 238 239 if not self.strategy.bankrupt: --> 240 self.strategy.run() 241 # need update after to save weights, values and such 242 self.strategy.update(dt)

    ~/opt/anaconda3/lib/python3.8/site-packages/bt/core.cpython-38-darwin.so in bt.core.Strategy.run()

    ~/opt/anaconda3/lib/python3.8/site-packages/bt/core.cpython-38-darwin.so in bt.core.AlgoStack.call()

    ~/opt/anaconda3/lib/python3.8/site-packages/bt/algos.py in call(self, target) 1810 # Turn off updating while we rebalance each child 1811 for item in iteritems(targets): -> 1812 target.rebalance(item[1], child=item[0], base=base, update=False) 1813 1814 # Now update

    ~/opt/anaconda3/lib/python3.8/site-packages/bt/core.cpython-38-darwin.so in bt.core.StrategyBase.rebalance()

    ~/opt/anaconda3/lib/python3.8/site-packages/bt/core.cpython-38-darwin.so in bt.core.SecurityBase.allocate()

    Exception: Cannot allocate capital to 0 because price is 0 as of 2020-06-25 00:00:00`

    opened by CDLim0906 10
  • Failed building wheel for bt issue

    Failed building wheel for bt issue

    Hi, i'm having a issue with to install bt on jupyter notebook. On Google Colab i'm installing without any problem at all. I found the same issue in this session 2 years ago, i did the same steps, but the error persists.

    image

    opened by bruno-albuquerque-solcap 10
  • Graph issue

    Graph issue

    Hi I tried to run the simple example from the doc:

    import bt
    import pandas as pd
    
    # fetch some data
    data = bt.get('spy,agg', start='2010-01-01')
    print(data.tail())
    
    s = bt.Strategy('s1', [bt.algos.RunMonthly(),
                           bt.algos.SelectAll(),
                           bt.algos.WeighEqually(),
                           bt.algos.Rebalance()])
    
    # create a backtest and run it
    test = bt.Backtest(s, data)
    res = bt.run(test)
    
    # first let's see an equity curve
    res.plot()
    

    But no graph appears as indicated in the manual. I just get:

    <AxesSubplot:title={'center':'Equity Progression'}>
    

    Then with

    res.plot_histogram()
    

    I get an error message:

    AttributeError: 'Rectangle' object has no property 'normed'
    

    and with:

    res.plot_security_weights()
    

    Nothing happens.

    Any suggestion ? Thx.

    opened by Jacques2101 9
  • bt install fails in fresh Anaconda environment (python3.7) on Win 10

    bt install fails in fresh Anaconda environment (python3.7) on Win 10

    This is odd, because I had installed it successfully before in Anaconda on this machine. But after a fresh Anaconda install, ffn is fine but not bt. Here is what it tells me:

    failed to build bt

    ERROR: Command errored out with exit status 1:
     command: 'E:\Anaconda3\envs\finance\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\ajryounger\\AppData\\Local\\Temp\\pip-install-p1ipp9lw\\bt\\setup.py'"'"'; __file__='"'"'C:\\Users\\ajryounger\\AppData\\Local\\Temp\\pip-install-p1ipp9lw\\bt\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\ajryounger\AppData\Local\Temp\pip-record-048hfjfz\install-record.txt' --single-version-externally-managed --compile --install-headers 'E:\Anaconda3\envs\finance\Include\bt'
         cwd: C:\Users\ajryounger\AppData\Local\Temp\pip-install-p1ipp9lw\bt\
    Complete output (13 lines):
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    creating build\lib.win-amd64-3.7\bt
    copying bt\algos.py -> build\lib.win-amd64-3.7\bt
    copying bt\backtest.py -> build\lib.win-amd64-3.7\bt
    copying bt\core.py -> build\lib.win-amd64-3.7\bt
    copying bt\__init__.py -> build\lib.win-amd64-3.7\bt
    running build_ext
    building 'bt.core' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/
    ----------------------------------------
    

    ERROR: Command errored out with exit status 1: 'E:\Anaconda3\envs\finance\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\ajryounger\AppData\Local\Temp\pip-install-p1ipp9lw\bt\setup.py'"'"'; file='"'"'C:\Users\ajryounger\AppData\Local\Temp\pip-install-p1ipp9lw\bt\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\ajryounger\AppData\Local\Temp\pip-record-048hfjfz\install-record.txt' --single-version-externally-managed --compile --install-headers 'E:\Anaconda3\envs\finance\Include\bt' Check the logs for full command output.

    I am not sure that I **really ** need to install an obsolete MS VC++! I have every one from the 2008 to the 2015-19 versions but not 2014 for whatever reasons.

    It's not fatal, because what I really use is ffn, but I though I would let you know. I really do appreciate both libraries and have had students in my financial theory course use bt in the past.

    sincerely a. younger

    opened by EcoFin 9
  • Float Division by Zero if not using Rebalance

    Float Division by Zero if not using Rebalance

    Thank you guys for creating this tool, it has been very useful so far in my testing. I apologize if this is not the right place to be asking this question, but I'm running into an issue.

    Testing out a simple strategy of 1.0 weight on a single equity, I'm able to produce results that broadly match a simple returns calculation (price.pct_change().cumsum()). I believe the difference in results is due to re-balancing, but when I try to run the test without the Rebalance algo, I get float division by zero error:

    <ipython-input-53-c33459b5d55d> in <module>()
    ----> 1 res = bt.run(t)
    
    C:\Users\dyang\AppData\Local\Continuum\Anaconda2\lib\site-packages\bt\backtest.pyc in run(*backtests)
         28         bkt.run()
         29
    ---> 30     return Result(*backtests)
         31
         32
    
    C:\Users\dyang\AppData\Local\Continuum\Anaconda2\lib\site-packages\bt\backtest.pyc in __init__(self, *backtests)
        315     def __init__(self, *backtests):
        316         tmp = [pd.DataFrame({x.name: x.strategy.prices}) for x in backtests]
    --> 317         super(Result, self).__init__(*tmp)
        318         self.backtest_list = backtests
        319         self.backtests = {x.name: x for x in backtests}
    
    C:\Users\dyang\AppData\Local\Continuum\Anaconda2\lib\site-packages\ffn\core.pyc in __init__(self, *prices)
        644         self._end = self._prices.index[-1]
        645         # calculate stats for entire series
    --> 646         self._update(self._prices)
        647
        648     def __getitem__(self, key):
    
    C:\Users\dyang\AppData\Local\Continuum\Anaconda2\lib\site-packages\ffn\core.pyc in _update(self, data)
        653
        654     def _update(self, data):
    --> 655         self._calculate(data)
        656         # lookback returns dataframe
        657         self.lookback_returns = pd.DataFrame(
    
    C:\Users\dyang\AppData\Local\Continuum\Anaconda2\lib\site-packages\ffn\core.pyc in _calculate(self, data)
        666         for c in data.columns:
        667             prc = data[c]
    --> 668             self[c] = PerformanceStats(prc)
        669
        670     def _stats(self):
    
    C:\Users\dyang\AppData\Local\Continuum\Anaconda2\lib\site-packages\ffn\core.pyc in __init__(self, prices, rf)
         61         self.rf = rf
         62
    ---> 63         self._update(self.prices)
         64
         65     def set_riskfree_rate(self, rf):
    
    C:\Users\dyang\AppData\Local\Continuum\Anaconda2\lib\site-packages\ffn\core.pyc in _update(self, obj)
         80     def _update(self, obj):
         81         # calc
    ---> 82         self._calculate(obj)
         83
         84         # update derived structure
    
    C:\Users\dyang\AppData\Local\Continuum\Anaconda2\lib\site-packages\ffn\core.pyc in _calculate(self, obj)
        188         self.daily_mean = r.mean() * 252
        189         self.daily_vol = r.std() * np.sqrt(252)
    --> 190         self.daily_sharpe = r.calc_sharpe(rf=self.rf, nperiods=252)
        191         self.daily_sortino = calc_sortino_ratio(r, rf=self.rf, nperiods=252)
        192         self.best_day = r.max()
    
    C:\Users\dyang\AppData\Local\Continuum\Anaconda2\lib\site-packages\ffn\core.pyc in calc_sharpe(returns, rf, nperiod
    s, annualize)
       1181
       1182     er = returns.to_excess_returns(rf, nperiods=nperiods)
    -> 1183     res = er.mean() / er.std()
       1184
       1185     if annualize:
    
    ZeroDivisionError: float division by zero
    

    I am using the same weights algo as shown in the SMA Cross example:

    class WeighTarget(bt.Algo):
    
    	def __init__(self, target_weights):
    		self.tw = target_weights
    
    	def __call__(self, target):
    		if target.now in self.tw.index:
    			w = self.tw.loc[target.now]
    
    			target.temp['weights'] = w.dropna()
    
    		return True
    

    Again, apologies if this is the wrong place to ask, 99% chance I'm just missing something, 1% chance this is a real "Issue"

    opened by yngstr 9
  • Rebalancing error: Cash management bug

    Rebalancing error: Cash management bug

    There is a problem in rebalancing implementation (rebalance() and its sister method). The cash target code goes into a infinite recursive loop if target weights are negative (short positions). (_I've also seen it happen even in a portfolio of positive weights with a commission function which may be causing cash to dip below)

    "Exception: Potentially infinite loop detected. This occured while trying to reduce the amount of shares purchased to respect the outlay <= amount rule. This is most likely due to a commission function that outputs a commission that is greater than the amount of cash a short sale can raise."

    ############# test.py ############### import pandas as pd import bt import datetime as dt import random

    date_span = pd.DatetimeIndex(start='10/1/2017', end='10/11/2017', freq='B') numper = len(date_span.values) comms = 0.01

    data = [[10,15,20,25,30,35,40,45], [10,10,10,10,20,20,20,20], [20,20,20,30,30,30,40,40], [20,10,20,10,20,10,20,10]] data = [[row[i] for row in data] for i in range(len(data[0]))] #Transpose price = pd.DataFrame(data=data, index=date_span) price.columns = ['a', 'b', 'c', 'd'] #price = price[['a', 'b']]

    sig1 = pd.DataFrame(price['a'] >= price['b'] +10, columns=['a']) sig2 = pd.DataFrame(price['a'] < price['b'] +10, columns=['b']) signal = sig1.join(sig2)

    signal1 = price.diff(1) > 0 signal2 = price.diff(1) < 0

    tw = price.copy() tw.set_value(tw.index,tw.columns,0) # Initialize Set everything to 0

    tw[signal1] = -1.0 tw[signal2] = 1.0

    s1 = bt.Strategy('long_short', [ bt.algos.WeighTarget(tw), bt.algos.RunDaily(), bt.algos.Rebalance()])

    ####now we create the Backtest , commissions=(lambda q, p: abs(p * q) * comms) t = bt.Backtest(s1, price, initial_capital=1000000, commissions=(lambda q, p: abs(p * q) * comms) )

    ####and let's run it! res = bt.run(t) ########################

    bug help wanted 
    opened by suhailmn 9
  • Long & Short

    Long & Short

    I would like to execute a long on a set of security and short in a index, like S&P. The short should be the same size of the long position.

    Does anyone has a sample of that? Is that possible?

    opened by pedrorjbr 0
  • I would like to get the Monthly Max Drawdown.

    I would like to get the Monthly Max Drawdown.

    Max Drawdown(MDD) of the .display() may be Daily MDD. But for most asset allocations, the MDD is based on a monthly basis. I hope monthly MDD would be added to result of the backtest.

    opened by pinedance 0
  • bt.algos.RunAfterDate can not update bt.backtest.Result ( 'Start', 'CARG' etc )

    bt.algos.RunAfterDate can not update bt.backtest.Result ( 'Start', 'CARG' etc )

    I am backtesting some momentum strategies with bt package. As you know, momentum strategies require a longer period of data than the trading period. So I added bt.algos.RunAfterDate to my strategies.

    I expected bt.backtest.Result should be chaged when bt.algos.RunAfterDate was added. But Start date of Result was still first date of the data. I doubt the accuracy of the CAGR value. Because CAGR is mostly affected by the trading period.

    I hope this part will be fixed.

    # Pseudocode
    # When first date of the data is 2000-01-01 ...
    my_strategy = [
        ...
        bt.algos.RunAfterDate("2001-01-01")
        ...
    ]
    
    # Result of my backtest
    Stat     my_strategy
    -----    --------------
    Start    2000-01-01       # not 2001-01-01
    ...
    CAGR     7.25             # derived based on data period or trading period?
    
    opened by pinedance 0
  • how i want buy at a and sell at b

    how i want buy at a and sell at b

    see the '' signal = data > sma '' in example, but if i have a indicator, when indicator < 10, i buy it; indicator > 50, sold it. how to implement this example.

    opened by hy2014 0
  • Short selling won't work

    Short selling won't work

    I'm trying to pass a negative weight list using the "WeighTarget" method, but it won't work. When I call "get_security_weights", the weight does not stand at -100%, it keeps moving (backtesting in only one security).

    When I set the "WeighTarget" to 100%, it works just fine.

    Anyone has a clue why short selling is not working?

    opened by Persevera-Asset-Management 0
Releases(v0.2.9)
  • v0.2.9(Apr 21, 2021)

  • v0.2.8(Feb 1, 2021)

    ~2 years of accumulated bug fixes and features. Many version compatibility modifications for new numpy, new pandas, new matplotlib, etc.

    Vastly expanded support for constructing fixed income strategies.

    Built for ffn >= 0.3.5

    Source code(tar.gz)
    Source code(zip)
Python Backtesting library for trading strategies

backtrader Yahoo API Note: [2018-11-16] After some testing it would seem that data downloads can be again relied upon over the web interface (or API v

DRo 9.8k Dec 30, 2022
A python wrapper for Alpha Vantage API for financial data.

alpha_vantage Python module to get stock data/cryptocurrencies from the Alpha Vantage API Alpha Vantage delivers a free API for real time financial da

Romel Torres 3.8k Jan 7, 2023
Portfolio and risk analytics in Python

pyfolio pyfolio is a Python library for performance and risk analysis of financial portfolios developed by Quantopian Inc. It works well with the Zipl

Quantopian, Inc. 4.8k Jan 8, 2023
Python sync/async framework for Interactive Brokers API

Introduction The goal of the IB-insync library is to make working with the Trader Workstation API from Interactive Brokers as easy as possible. The ma

Ewald de Wit 2k Dec 30, 2022
ffn - a financial function library for Python

ffn - Financial Functions for Python Alpha release - please let me know if you find any bugs! If you are looking for a full backtesting framework, ple

Philippe Morissette 1.4k Jan 1, 2023
An Algorithmic Trading Library for Crypto-Assets in Python

Service Master Develop CI Badge Catalyst is an algorithmic trading library for crypto-assets written in Python. It allows trading strategies to be eas

Enigma 2.4k Jan 5, 2023
Python Algorithmic Trading Library

PyAlgoTrade PyAlgoTrade is an event driven algorithmic trading Python library. Although the initial focus was on backtesting, paper trading is now pos

Gabriel Becedillas 3.9k Jan 1, 2023
ARCH models in Python

arch Autoregressive Conditional Heteroskedasticity (ARCH) and other tools for financial econometrics, written in Python (with Cython and/or Numba used

Kevin Sheppard 1k Jan 4, 2023
:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.

Backtesting.py Backtest trading strategies with Python. Project website Documentation the project if you use it. Installation $ pip install backtestin

null 3.1k Dec 31, 2022
Q-Fin: A Python library for mathematical finance.

Q-Fin A Python library for mathematical finance. Installation https://pypi.org/project/QFin/ pip install qfin Bond Pricing Option Pricing Black-Schol

Roman Paolucci 247 Jan 1, 2023
personal finance tracker, written in python 3 and using the wxPython GUI toolkit.

personal finance tracker, written in python 3 and using the wxPython GUI toolkit.

wenbin wu 23 Oct 30, 2022
Beibo is a Python library that uses several AI prediction models to predict stocks returns over a defined period of time.

Beibo is a Python library that uses several AI prediction models to predict stocks returns over a defined period of time.

Santosh 54 Dec 10, 2022
Indicator divergence library for python

Indicator divergence library This module aims to help to find bullish/bearish divergences (regular or hidden) between two indicators using argrelextre

null 8 Dec 13, 2022
Python library for backtesting trading strategies & analyzing financial markets (formerly pythalesians)

finmarketpy (formerly pythalesians) finmarketpy is a Python based library that enables you to analyze market data and also to backtest trading strateg

Cuemacro 3k Dec 30, 2022
Python Backtesting library for trading strategies

backtrader Yahoo API Note: [2018-11-16] After some testing it would seem that data downloads can be again relied upon over the web interface (or API v

DRo 9.8k Dec 30, 2022
A Python-based development platform for automated trading systems - from backtesting to optimisation to livetrading.

AutoTrader AutoTrader is Python-based platform intended to help in the development, optimisation and deployment of automated trading systems. From sim

Kieran Mackle 485 Jan 9, 2023
Trading and Backtesting environment for training reinforcement learning agent or simple rule base algo.

TradingGym TradingGym is a toolkit for training and backtesting the reinforcement learning algorithms. This was inspired by OpenAI Gym and imitated th

Yvictor 1.1k Jan 2, 2023
Scalable, event-driven, deep-learning-friendly backtesting library

...Minimizing the mean square error on future experience. - Richard S. Sutton BTGym Scalable event-driven RL-friendly backtesting library. Build on

Andrew 922 Dec 27, 2022
Trading environnement for RL agents, backtesting and training.

TradzQAI Trading environnement for RL agents, backtesting and training. Live session with coinbasepro-python is finaly arrived ! Available sessions: L

Tony Denion 164 Oct 30, 2022
This is a simple backtesting framework to help you test your crypto currency trading. It includes a way to download and store historical crypto data and to execute a trading strategy.

You can use this simple crypto backtesting script to ensure your trading strategy is successful Minimal setup required and works well with static TP a

Andrei 154 Sep 12, 2022