Portfolio and risk analytics in Python

Related tags

Financepyfolio
Overview

pyfolio

pyfolio

Join the chat at https://gitter.im/quantopian/pyfolio build status

pyfolio is a Python library for performance and risk analysis of financial portfolios developed by Quantopian Inc. It works well with the Zipline open source backtesting library. Quantopian also offers a fully managed service for professionals that includes Zipline, Alphalens, Pyfolio, FactSet data, and more.

At the core of pyfolio is a so-called tear sheet that consists of various individual plots that provide a comprehensive image of the performance of a trading algorithm. Here's an example of a simple tear sheet analyzing a strategy:

simple tear 0 simple tear 1

Also see slides of a talk about pyfolio.

Installation

To install pyfolio, run:

pip install pyfolio

Development

For development, you may want to use a virtual environment to avoid dependency conflicts between pyfolio and other Python projects you have. To get set up with a virtual env, run:

mkvirtualenv pyfolio

Next, clone this git repository and run python setup.py develop and edit the library files directly.

Matplotlib on OSX

If you are on OSX and using a non-framework build of Python, you may need to set your backend:

echo "backend: TkAgg" > ~/.matplotlib/matplotlibrc

Usage

A good way to get started is to run the pyfolio examples in a Jupyter notebook. To do this, you first want to start a Jupyter notebook server:

jupyter notebook

From the notebook list page, navigate to the pyfolio examples directory and open a notebook. Execute the code in a notebook cell by clicking on it and hitting Shift+Enter.

Questions?

If you find a bug, feel free to open an issue in this repository.

You can also join our mailing list or our Gitter channel.

Support

Please open an issue for support.

Contributing

If you'd like to contribute, a great place to look is the issues marked with help-wanted.

For a list of core developers and outside collaborators, see the GitHub contributors list.

Comments
  • AttributeError: 'numpy.int64' object has no attribute 'to_pydatetime'

    AttributeError: 'numpy.int64' object has no attribute 'to_pydatetime'

    occurs when trying to run an example from the docs

    stock_rets = pf.utils.get_symbol_rets('FB')
    pf.create_returns_tear_sheet(stock_rets, live_start_date='2015-12-1')
    
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-40-feb97330a052> in <module>()
    ----> 1 pf.create_returns_tear_sheet(df, benchmark_rets=benchmark_rets)
    
    ~/.pyenv/versions/3.6.0/envs/pyfolio/lib/python3.6/site-packages/pyfolio/plotting.py in call_w_context(*args, **kwargs)
         50         if set_context:
         51             with plotting_context(), axes_style():
    ---> 52                 return func(*args, **kwargs)
         53         else:
         54             return func(*args, **kwargs)
    
    ~/.pyenv/versions/3.6.0/envs/pyfolio/lib/python3.6/site-packages/pyfolio/tears.py in create_returns_tear_sheet(returns, positions, transactions, live_start_date, cone_std, benchmark_rets, bootstrap, return_fig)
        455                              live_start_date=live_start_date)
        456 
    --> 457     plotting.show_worst_drawdown_periods(returns)
        458 
        459     # If the strategy's history is longer than the benchmark's, limit strategy
    
    ~/.pyenv/versions/3.6.0/envs/pyfolio/lib/python3.6/site-packages/pyfolio/plotting.py in show_worst_drawdown_periods(returns, top)
       1686     """
       1687 
    -> 1688     drawdown_df = timeseries.gen_drawdown_table(returns, top=top)
       1689     utils.print_table(drawdown_df.sort_values('Net drawdown in %',
       1690                                               ascending=False),
    
    ~/.pyenv/versions/3.6.0/envs/pyfolio/lib/python3.6/site-packages/pyfolio/timeseries.py in gen_drawdown_table(returns, top)
        995                                                                 recovery,
        996                                                                 freq='B'))
    --> 997         df_drawdowns.loc[i, 'Peak date'] = (peak.to_pydatetime()
        998                                             .strftime('%Y-%m-%d'))
        999         df_drawdowns.loc[i, 'Valley date'] = (valley.to_pydatetime()
    
    AttributeError: 'numpy.int64' object has no attribute 'to_pydatetime'
    
    bug 
    opened by kwangbkim 38
  • pyfolio output is not displaying cleanly

    pyfolio output is not displaying cleanly

    Hi I am new to using python and have been working with pyfolio to generate the graphs for portfolio returns. I am getting a the following figure. Any help would be appreciated. Thanks

    image

    opened by chhab 25
  • MAINT: update perf attrib summary table

    MAINT: update perf attrib summary table

    update summary table to be of the format:

    Summary statistics:
    Annualized Specific Return (Alpha): x%
    Annualized Common Return (Beta): y%
    Total Annualized Return: A%
    
    Specific Sharpe Ratio: x%/std.dev()
    

    annualized cost to be added later on.

    cc @joshpayne

    opened by vikram-narayan 23
  • MAINT Make long/short positions match gross leverage

    MAINT Make long/short positions match gross leverage

    This makes pos.get_long_short_pos return a dataframe that matches the gross leverage of the portfolio.

    I removed the gross_lev argument since the leverage is dependent on positions dataframe.

    This PR is addressing https://github.com/quantopian/pyfolio/issues/30

    opened by humdings 21
  • IndexError: invalid index

    IndexError: invalid index

    hi I am using pyfolio 0.9.0 and pandas 0.22

    Got an error below(although the program continue running and plot graphs), does anyone have ideas?

    Thanks a lot!

    ======== IndexErrorTraceback (most recent call last) in () ----> 1 pf.create_returns_tear_sheet(stock_rets, benchmark_rets=benchmark_rets)

    /home/frank/Envs/quants/local/lib/python2.7/site-packages/pyfolio/plotting.pyc in call_w_context(*args, **kwargs) 50 if set_context: 51 with plotting_context(), axes_style(): ---> 52 return func(*args, **kwargs) 53 else: 54 return func(*args, **kwargs)

    /home/frank/Envs/quants/local/lib/python2.7/site-packages/pyfolio/tears.pyc in create_returns_tear_sheet(returns, positions, transactions, live_start_date, cone_std, benchmark_rets, bootstrap, turnover_denom, header_rows, return_fig) 641 if ((bootstrap is not None) 642 and (benchmark_rets is not None)): --> 643 ax_bootstrap = plt.subplot(gs[i, :]) 644 plotting.plot_perf_stats(returns, benchmark_rets, 645 ax=ax_bootstrap)

    /home/frank/Envs/quants/local/lib/python2.7/site-packages/matplotlib/gridspec.pyc in getitem(self, key) 159 raise ValueError("unrecognized subplot spec") 160 num1, num2 = np.ravel_multi_index( --> 161 [_normalize(k1, nrows), _normalize(k2, ncols)], (nrows, ncols)) 162 else: # Single key 163 num1, num2 = _normalize(key, nrows * ncols)

    /home/frank/Envs/quants/local/lib/python2.7/site-packages/matplotlib/gridspec.pyc in _normalize(key, size) 151 if 0 <= key < size: 152 return key, key --> 153 raise IndexError("invalid index") 154 155 if isinstance(key, tuple):

    IndexError: invalid index

    bug help wanted high priority 
    opened by fzhcary 20
  • Importing pyfolio implicitly imports every module in PyFolio

    Importing pyfolio implicitly imports every module in PyFolio

    This has two major negative consequences:

    1. During development, an import-time error (e.g. a syntax error, or a missing package) anywhere in the repo causes all imports to fail.
    2. Importing anything in the library takes an annoyingly long (almost 3 seconds on my machine) amount of time. Most of this time is spent in seaborn.__init__.

    @twiecki is there a reason we're doing this in the module __init__?

    from . import utils
    from . import timeseries
    from . import pos
    from . import txn
    
    from .tears import *  # noqa
    from .plotting import *  # noqa
    
    opened by ssanderson 18
  • Fama-French multivariate regression

    Fama-French multivariate regression

    Fixes #379

    We don't just want a multivariate regression, we want a rolling multivariate regression. Pandas used to support this sort of thing with pd.stats.ols.MovingOLS, but that has unfortunately been deprecated.

    A solution is described on StackOverflow, but frustratingly this solution doesn't work since apply only works on Series data (see citynorman's comment on the top answer). So, we will have to write our own rolling multivariate regression...

    bug 
    opened by eigenfoo 17
  • Fix deprecations and remove Bayesian models

    Fix deprecations and remove Bayesian models

    This fixes a whole bunch of stuff that caused tests to break under more recent python and pandas. It also removes the bayesian module, it's just making tests slow, is difficult to install, and we don't have time to maintain it properly.

    opened by twiecki 16
  • Pandas error when running the single stock example

    Pandas error when running the single stock example

    Hi, I am running the single stock example. As I run the line:

    pf.create_returns_tear_sheet(stock_rets, live_start_date='2015-12-1')

    I obtain the following error:

    /lib/python3.4/site-packages/pandas/tseries/tools.py in _convert_listlike(arg, box, format, name) 329 arg = getattr(arg, 'values', arg) 330 result = tslib.array_with_unit_to_datetime(arg, unit, --> 331 errors=errors) 332 if box: 333 if errors == 'ignore': pandas/tslib.pyx in pandas.tslib.array_with_unit_to_datetime (pandas/tslib.c:38273)() pandas/tslib.pyx in pandas.tslib.array_with_unit_to_datetime (pandas/tslib.c:37194)() ValueError: non convertible value 2015-07-21with the unit 'D'

    bug help wanted high priority 
    opened by fretchen 16
  • New release for pyfolio

    New release for pyfolio

    It looks like enough has changed on pyfolio to merit v0.8.0 (with risk and performance attribution, I think we might even want to call it v1.0.0!)

    We are also seeing an increasing number of users running into bugs that have already been patched: upping the version would make it easier to diagnose errors (both ours, and open source users).

    To-do:

    • [ ] Performance attribution tear sheet #417 (still WIP, will definitely want to wait for this)
    • [ ] Resolve any dependency issues with zipline/alphalens/empyrical
    • [x] Do we want to outsource Fama-French functionality from pyfolio to empyrical? #56 on empyrical (Answer: yes. PR waiting: #416)
    • [ ] Do we want to include returns decomposition from alphalens into pyfolio? #183 on alphalens

    @twiecki @gusgordon @richafrank @Jstauth thoughts? If this sounds good I'll organize a milestone :)

    New features

    • Risk tear sheet: added a new tear sheet to analyze risk exposures to common factors, sector, market cap and illiquidity (#391)
    • Simple tear sheet: added a new tear sheet that presents only the most important plots in the full tear sheet, for a quick general overview of a portfolio's performance (#389)
    • Volatility plot: added a rolling annual volatility plot in the returns tear sheet (#390)

    Bugfixes

    • Fixed bug regarding Yahoo API and pandas data reader (#395)
    • Removed information_ratio to remain compatible with empyrical
    • Fama-French rolling multivariate regression bug fix (#406)

    Maintenance

    • Updated and improved jupyter notebook documentation (#411)
    opened by eigenfoo 15
  • replaced yahoo backend with google for market data

    replaced yahoo backend with google for market data

    Referencing issue: #385

    I have substituted out the yahoo backend for the google data using the pandas web.get_data_google(symbol, start=start, end=end) function

    opened by closedLoop 15
  • backtrader

    backtrader

    Problem Description

    Please provide a minimal, self-contained, and reproducible example:

    [Paste code here]
    

    Please provide the full traceback:

    [Paste traceback here]
    

    Please provide any additional information below:

    Versions

    • Pyfolio version:
    • Python version:
    • Pandas version:
    • Matplotlib version:
    opened by zhaole0452 0
  • Added return_fig boolean parameter to create_full_tear_sheet() and create_simple_tear_sheet()

    Added return_fig boolean parameter to create_full_tear_sheet() and create_simple_tear_sheet()

    Modified create_full_tear_sheet() and create_simple_tear_sheet() to optionally return matplotlib figures based on the return_fig boolean parameter, in analogy to other tear sheet functions, such as create_returns_tear_sheet(), create_position_tear_sheet() etc. Now these two tear sheet functions can be used outside of IPython (%matplotlib inline) environments to capture these tear sheets and display them, convert them to pdf files etc.

    If return_fig==True, create_full_tear_sheet() now returns the following dictionary containing all the matplotlib figures that were created internally:

    { 'returns': fig_returns, 'interesting_times': fig_interesting_times, 'position': fig_position, 'txn': fig_txn, 'round_trip': fig_round_trip, 'capacity': fig_capacity, 'perf_attrib': fig_perf_attrib }

    And if return_fig==True, create_simple_tear_sheet() returns the matplotlib figure already created internally.

    opened by nikoulis 0
  • TypeError: an integer is required (got type bytes)

    TypeError: an integer is required (got type bytes)

    Problem Description

    Please provide a minimal, self-contained, and reproducible example:

    [Paste code here]
    

    import pyfolio as pf Please provide the full traceback:

    [Paste traceback here]
    ```---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-11-1977abd82007> in <module>
    ----> 1 import pyfolio as pf
    
    ~\anaconda3\lib\site-packages\pyfolio\__init__.py in <module>
    ----> 1 from . import utils
          2 from . import timeseries
          3 from . import pos
          4 from . import txn
          5 from . import interesting_periods
    
    ~\anaconda3\lib\site-packages\pyfolio\utils.py in <module>
         26 import empyrical.utils
         27 
    ---> 28 from . import pos
         29 from . import txn
         30 
    
    ~\anaconda3\lib\site-packages\pyfolio\pos.py in <module>
         20 
         21 try:
    ---> 22     from zipline.assets import Equity, Future
         23     ZIPLINE = True
         24 except ImportError:
    
    c:\users\home\src\zipline-trader\zipline\__init__.py in <module>
         27 from .utils.numpy_utils import numpy_version
         28 from .utils.pandas_utils import new_pandas
    ---> 29 from .utils.run_algo import run_algorithm
         30 from ._version import get_versions
         31 
    
    c:\users\home\src\zipline-trader\zipline\utils\run_algo.py in <module>
         22 from trading_calendars import get_calendar
         23 
    ---> 24 from zipline.data import bundles
         25 from zipline.data.benchmarks import get_benchmark_returns_from_file
         26 from zipline.data.data_portal import DataPortal
    
    c:\users\home\src\zipline-trader\zipline\data\bundles\__init__.py in <module>
          1 # These imports are necessary to force module-scope register calls to happen.
    ----> 2 from . import quandl  # noqa
          3 from . import csvdir  # noqa
          4 from . import alpaca_api
          5 from . import alpha_vantage_api
    
    c:\users\home\src\zipline-trader\zipline\data\bundles\quandl.py in <module>
         14 from trading_calendars import register_calendar_alias
         15 
    ---> 16 from . import core as bundles
         17 import numpy as np
         18 
    
    c:\users\home\src\zipline-trader\zipline\data\bundles\core.py in <module>
         11 from toolz import curry, complement, take
         12 
    ---> 13 from ..adjustments import SQLiteAdjustmentReader, SQLiteAdjustmentWriter
         14 from ..bcolz_daily_bars import BcolzDailyBarReader, BcolzDailyBarWriter
         15 from ..minute_bars import (
    
    c:\users\home\src\zipline-trader\zipline\data\adjustments.py in <module>
         27 from zipline.utils.pandas_utils import empty_dataframe
         28 from zipline.utils.db_utils import group_into_chunks, coerce_string_to_conn
    ---> 29 from ._adjustments import load_adjustments_from_sqlite
         30 
         31 log = Logger(__name__)
    
    c:\users\home\src\zipline-trader\zipline\data\_adjustments.pyx in init zipline.data._adjustments()
    
    c:\users\home\src\zipline-trader\zipline\assets\__init__.py in <module>
         20     make_asset_array,
         21 )
    ---> 22 from .assets import (
         23     AssetFinder,
         24     AssetConvertible,
    
    c:\users\home\src\zipline-trader\zipline\assets\assets.py in <module>
         65     OrderedContracts,
         66 )
    ---> 67 from .asset_writer import (
         68     check_version_info,
         69     split_delimited_symbol,
    
    c:\users\home\src\zipline-trader\zipline\assets\asset_writer.py in <module>
        451 
        452 
    --> 453 class AssetDBWriter(object):
        454     """Class used to write data to an assets db.
        455 
    
    c:\users\home\src\zipline-trader\zipline\assets\asset_writer.py in AssetDBWriter()
        462 
        463     @preprocess(engine=coerce_string_to_eng(require_exists=False))
    --> 464     def __init__(self, engine, asset_finder=None):
        465         self.asset_finder = asset_finder
        466         self.engine = engine
    
    c:\users\home\src\zipline-trader\zipline\utils\preprocess.py in _decorator(f)
        107             )
        108 
    --> 109         return _build_preprocessed_function(
        110             f, processors, args_defaults, varargs, varkw,
        111         )
    
    c:\users\home\src\zipline-trader\zipline\utils\preprocess.py in _build_preprocessed_function(func, processors, args_defaults, varargs, varkw)
        244 
        245     args['co_firstlineno'] = original_code.co_firstlineno
    --> 246     new_func.__code__ = CodeType(*map(getitem(args), _code_argorder))
        247     return new_func
    
    TypeError: an integer is required (got type bytes)
    
    
    
    
    
    
    **Please provide any additional information below:**
    
    
    ## Versions
    
    * Pyfolio version:      3
    * Python version:      3.8.5
    * Pandas version:      1.1.3
    * Matplotlib version:  3.32
    
    opened by cdsmumbai 0
  • Export output

    Export output

    Problem Description

    Please provide a minimal, self-contained, and reproducible example:

    f = pf.create_returns_tear_sheet(df, benchmark_rets=benchmark_rets,return_fig=True);
    f.savefig('report.pdf')
    

    Please provide the full traceback:

    how we can export the full output? I use savefig(), but it saves only plots , and doesn't save  fists part of output
    
    
    

    Please provide any additional information below:

    saved filed didn't contain tabular part, for example these two tables image , saved only plots.

    Versions

    • Pyfolio version: 0.9.4
    • Python version: 3.7
    • Pandas version:1.3.5
    • Matplotlib version: 3.5.2
    opened by TaguhiSekhleyan 0
  • Quantopian/pyfolio is NO LONGER MAINTAINED - See other forks

    Quantopian/pyfolio is NO LONGER MAINTAINED - See other forks

    Any issues raised for in this Git are unlikely to be resolved, since Quantopian has folded and the staff that have moved to Robinhood have not been involved for a few years, so it's currently unlikely that anything will happen here.

    However, thanks to the foresight of the Quantopian founders and devs who made this open source, other contributors have taken the banner and have improved this package from where Quantopian left it.

    @Stefan-Jansen maintains a forked, updated version of this package here: https://github.com/stefan-jansen/pyfolio-reloaded

    as part of his continuing development of Zipline (also developed by Quantopian) here: https://github.com/stefan-jansen/zipline-reloaded

    opened by RichardDale 0
Releases(0.9.2)
  • 0.9.1(Feb 20, 2019)

  • 0.9.0(Aug 1, 2018)

    New features

    • Previously, pyfolio has required a benchmark, usually the U.S. market returns SPY. In order to provide support for international equities and alternative data sets, pyfolio is now completely independent of benchmarks. If a benchmark is passed, all benchmark-related analyses will be performed; if not, they will simply be skipped. By George Ho
    • Performance attribution tearsheet PR441, PR433, PR442. By Vikram Narayan.
    • Improved implementation of get_turnover PR332. By Gus Gordon.
    • Users can now pass in extra rows (as a dict or OrderedDict) to display in the perf_stats table PR445. By Gus Gordon.

    Maintenance

    Source code(tar.gz)
    Source code(zip)
  • v0.8.0(Aug 31, 2017)

    This is a major release from 0.7.0, and all users are recommended to upgrade.

    New features

    • Adds a new risk tear sheet that analyzes the risk exposures of the portfolio. Generates analysis showing the portfolio's exposures to common factors such as momentum and mean reversion, the portfolio's gross and net exposure to each sector, the gross and net exposure to each market cap bucket, and the overall exposure to illiquid stocks.
    • Adds a new performance attribution tear sheet that analyzes how much of the portfolio's returns is attributable to common factors (e.g. sector or style factors). Generates analysis showing the exposure to, and PnL generated by, common factors.
    • Adds a new simple tear sheet to provide a quick summary analysis using the most important plots in the full tear sheet.
    • Adds a rolling annual volatility plot to the returns tear sheet.
    • Adds new features to performance statistics summary table.

    Bugfixes

    • Bug fix with Yahoo and pandas data reader.
    • Rolling Fama-French exposures now performs a multivariate regression instead of multiple linear regressions.
    • Removed information_ratio to remain compatible with empyrical.

    Maintenance

    • Migrated Fama-French data loaders from pyfolio to empyrical. utils.load_portfolio_risk_factors is now deprecated in pyfolio, please use the same function in empyrical.
    • Minor decorative changes to plots, particularly the holdings plots.
    Source code(tar.gz)
    Source code(zip)
  • v0.7.0(Jan 27, 2017)

    This is a major release from 0.6.0, and all users are recommended to upgrade.

    New features

    • Adds a transaction timing plot, which gives insight into the strategies' trade times.
    • Adds a plot showing the number of longs and shorts held over time.
    • New round trips plot selects a sample of held positions (16 by default) and shows their round trips. This replaces the old round trip plot, which became unreadable for strategies that traded many positions.
    • Adds basic capability for analyzing intraday strategies. If a strategy makes a large amount of transactions relative to its end-of-day positions, then pyfolio will attempt to reconstruct the intraday positions, take the point of peak exposure to the market during each day, and plot that data with the positions tear sheet. By default pyfolio will automatically detect this, but the behavior can be changed by passing either estimate_intraday=True or estimate_intraday=False to the tear sheet functions (see here).
    • Now formats zipline assets, displaying their ticker symbol.
    • Gross leverage is no longer required to be passed, and will now be calculated from the passed positions DataFrame.

    Bugfixes

    • Cone plotting location is now correct.
    • Adjust scaling of beta and Fama-French plots.
    • Removed multiple dependencies, some of which were previously unused.
    • Various text fixes.
    Source code(tar.gz)
    Source code(zip)
  • v0.6.0(Oct 17, 2016)

    This is a major new release from 0.5.1. All users are recommended to upgrade.

    New features

    • Computation of performance and risk measures has been split off into empyrical. This allows Zipline and pyfolio to use the same code to calculate its risk statistics. By Ana Ruelas and Abhi Kalyan.
    • New multistrike cone which redraws the cone when it crossed its initial bounds PR310. By Ana Ruelas and Abhi Kalyan.

    Bugfixes

    • Can use most recent PyMC3 now.
    • Depends on seaborn 0.7.0 or later now PR331.
    • Disable buggy computation of round trips per day and per month PR339.
    Source code(tar.gz)
    Source code(zip)
  • v0.5.0(Apr 21, 2016)

    v0.5.1 (June, 10, 2016)

    This is a bugfix release from 0.5.0 with limited new functionality. All users are recommended to upgrade.

    New features

    Bugfixes

    • Fix drawdown behavior and pandas exception in tear-sheet creation PR297 by Flavio Duarte
    Source code(tar.gz)
    Source code(zip)
  • v0.3.1(Nov 12, 2015)

    This is a minor release from 0.3 that includes mostly bugfixes but also some new features. We recommend that all users upgrade to this new version.

    New features

    • Add Information Ratio PR194 by @MridulS
    • Bayesian tear-sheet now accepts 'Fama-French' option to do Bayesian multivariate regression against Fama-French risk factors PR200 by Shane Bussman
    • Plotting of monthly returns PR195

    Bug fixes

    • pos.get_percent_alloc was not handling short allocations correctly PR201
    • UTC bug with cached Fama-French factors commit
    • Sector map was not being passed from create_returns_tearsheet commit
    • New sector mapping feature was not Python 3 compatible PR201

    Maintenance

    • We now depend on pandas-datareader as the yahoo finance loaders from pandas will be deprecated PR181 by @tswrightsandpointe

    Contributors

    Besiders the core developers, we have seen an increase in outside contributions which we greatly appreciate. Specifically, these people contributed to this release:

    • Shane Bussman
    • @MridulS
    • @YihaoLu
    • @jkrauss82
    • @tswrightsandpointe
    • @cgdeboer
    Source code(tar.gz)
    Source code(zip)
Owner
Quantopian, Inc.
Quantopian builds software tools and libraries for quantitative finance.
Quantopian, Inc.
scrilla: A Financial Optimization Application

A python application that wraps around AlphaVantage, Quandl and IEX APIs, calculates financial statistics and optimizes portfolio allocations.

Grant Moore 6 Dec 17, 2022
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 01, 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

3.1k Dec 31, 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
Find big moving stocks before they move using machine learning and anomaly detection

Surpriver - Find High Moving Stocks before they Move Find high moving stocks before they move using anomaly detection and machine learning. Surpriver

Tradytics 1.5k Dec 31, 2022
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
A proper portfolio tracker. Featuring historical allocation, cash flows and real returns.

Python Portfolio Analytics A portfolio tracker featuring account transactions, historical allocation, dividends and splits management and endless perf

Simone Precicchiani 13 Aug 13, 2022
Common financial technical indicators implemented in Pandas.

FinTA (Financial Technical Analysis) Common financial technical indicators implemented in Pandas. This is work in progress, bugs are expected and resu

1.8k Dec 31, 2022
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 04, 2023
This repository contains a set of plugins for Volatility 3

volatility_plugins This repository contains a set of plugins for Volatility 3 These plugins are not compatible with Volatility 2 To use these plugins

Immersive-Labs-Sec 10 Nov 30, 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 01, 2023
rotki is an open source portfolio tracking, analytics, accounting and tax reporting tool that respects your privacy.

rotki is an open source portfolio tracking, analytics, accounting and tax reporting tool that respects your privacy. The mission of rotki is to bring transparency into the crypto and financial sector

Rotki 2k Dec 30, 2022
Performance analysis of predictive (alpha) stock factors

Alphalens Alphalens is a Python Library for performance analysis of predictive (alpha) stock factors. Alphalens works great with the Zipline open sour

Quantopian, Inc. 2.5k Dec 28, 2022
Yahoo! Finance market data downloader (+faster Pandas Datareader)

Yahoo! Finance market data downloader Ever since Yahoo! finance decommissioned their historical data API, many programs that relied on it to stop work

Ran Aroussi 8.4k Jan 01, 2023
Technical Analysis Library using Pandas and Numpy

Technical Analysis Library in Python It is a Technical Analysis library useful to do feature engineering from financial time series datasets (Open, Cl

Darío López Padial 3.4k Jan 02, 2023
This repository provides all Python codes and Jupyter Notebooks of the book Python for Finance

Python for Finance (O'Reilly) This repository provides all Python codes and Jupyter Notebooks of the book Python for Finance -- Analyze Big Financial

Yves Hilpisch 1.6k Jan 03, 2023
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 01, 2023
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
Supply a wrapper ``StockDataFrame`` based on the ``pandas.DataFrame`` with inline stock statistics/indicators support.

Stock Statistics/Indicators Calculation Helper VERSION: 0.3.2 Introduction Supply a wrapper StockDataFrame based on the pandas.DataFrame with inline s

Cedric Zhuang 1.1k Dec 28, 2022
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 08, 2023