ffn - a financial function library for Python

Related tags

Finance ffn
Overview

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

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, please check out bt. bt is built atop ffn and makes it easy and fast to backtest quantitative strategies.

Overview

ffn is a library that contains many useful functions for those who work in quantitative finance. It stands on the shoulders of giants (Pandas, Numpy, Scipy, etc.) and provides a vast array of utilities, from performance measurement and evaluation to graphing and common data transformations.

>> import ffn
>> returns = ffn.get('aapl,msft,c,gs,ge', start='2010-01-01').to_returns().dropna()
>> returns.calc_mean_var_weights().as_format('.2%')
aapl    62.54%
c       -0.00%
ge      36.19%
gs      -0.00%
msft     1.26%
dtype: object

Installation

The easiest way to install ffn is from the Python Package Index using pip or easy_install:

$ pip install ffn

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

ffn should be compatible with Python 2.7 and Python 3.

Documentation

Read the docs at http://pmorissette.github.io/ffn

Special Thanks

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

License

MIT

Comments
  • Runtime error

    Runtime error

    I am running the calc_stats() function on my data frame whihc seems to be formatted correctly and has no errors ( i tried it on the 297 lines of data then 50 then 10, errors on all the different frames), i get the following error: C:\ProgramData\Anaconda3\lib\site-packages\ffn\core.py:2054: RuntimeWarning: invalid value encountered in minimum negative_returns = np.minimum(returns, 0.)

    I am not very proficient in Python but i have done my best to see whats wrong with the data and it all looks clean. I am not using Yahoo data as the data retrieval that ffn is using also fails me, so I created my own data from elsewhere. Pls help as this would be very valuable to my project.

    Thanks

    opened by ShreyasChari 12
  • The 'warn' parameter of use() is deprecated since Matplotlib 3.1 and will be removed in 3.3.

    The 'warn' parameter of use() is deprecated since Matplotlib 3.1 and will be removed in 3.3.

    When I import fan I have this error. I've tried to update fun.

    `/opt/anaconda3/lib/python3.8/site-packages/ffn/core.py:27: MatplotlibDeprecationWarning:

    The 'warn' parameter of use() is deprecated since Matplotlib 3.1 and will be removed in 3.3. If any parameter follows 'warn', they should be pass as keyword, not positionally.`

    opened by MatteoSid 7
  • Added Calmar and Sortino ratios

    Added Calmar and Sortino ratios

    As per issue https://github.com/pmorissette/ffn/issues/10.

    For the Calmar Ratio I used the method discussed here: http://investexcel.net/calmar-ratio/ For the Sortino Ratio I used this method: http://investexcel.net/calculate-the-sortino-ratio-with-excel/

    I think I've implemented them correctly, but it might need a skilled eye to sense check it :)

    opened by Anjum48 7
  • Several functions using DataFrame.ix which has been removed from Pandas 1.0.0

    Several functions using DataFrame.ix which has been removed from Pandas 1.0.0

    Pandas 1.0.0 has removed the DataFrame.ix indexer. This indexer was being used in several core functions including rebase() and calc_cagr(). In all, there are 11 instances of this indexer being used in the core module. Pandas also seems to have become aggressive in their policy of requiring users to update. It would be good to update the indexer to the suggested .iloc or .loc, as appropriate.

    opened by neelotpal1112 6
  • Replacing ffn with empyrical and pyfolio

    Replacing ffn with empyrical and pyfolio

    Maybe we should just use empyricaland pyfolioinstead of ffn. @pmorissette @FinQuest What do you guys think?

    They seem similar and they have a strong community already. empyrical can replace the generic functions in ffn and pyfolio can replace PerformanceStats. We could still use ffn for calculations that they don't include like calc_mean_var_weights or calc_erc_weights but we wouldn't have to worry about maintaining the portfolio statistics or plots. Over time we could see about contributing any functionality they don't include into their libraries.

    I still prefer bt over zipline because it is easier to understand and verify the functionality is correct. Trusting the backtesting tool is essential if you are going to use the results to put money to work.

    opened by JordanPlatts 6
  • ffn.core.to_monthly not picking the last month?

    ffn.core.to_monthly not picking the last month?

    Hi,firstly i want to say thank you! this is an awesome package for financial researchers.

    This is my code -

    from pandas.io.data import DataReader import ffn moat=DataReader('MOAT','yahoo').reset_index().loc[:,['Date','Adj Close']].set_index('Date') moat=moat[moat.index<='31-aug-2014'] moat.tail() ffn.core.to_monthly(moat).tail()

    my question is, why do we not see the August data after converting to monthly?

    opened by sivananth 6
  • Cannot Download Data Due to

    Cannot Download Data Due to "RemoteDataError"

    Hi all,

    Two days ago, I tried to use ffn to get data from yahoo finance (by default), but the program left this error message to me.

    My statement was:

    aapl = ffn.get("aapl", start = "2020-05-06")

    The program showed me:

    RemoteDataError: Unable to read URL: https://finance.yahoo.com/quote/aapl/history?period1=1588737600&period2=1625371199&interval=1d&frequency=1d&filter=history

    I have tried different ticks and doublechecked the usage manual to see if any API is changed, but in vain. So would you please help me solve this issue? Thank you.

    BR, Arthur

    opened by arthurzllu 5
  • Update ytd and mtd calculation

    Update ytd and mtd calculation

    Fixed bug in YTD and MTD calculation. YTD and MTD are not calculated for short return series, and are not necessarily equal to total_return.

    MTD is only assigned something other than total_return, if more than one monthly return exists - which is unnecessary.

    Same issue for YTD - but with a stricter condition of more data before it is calculated.

    MTD and YTD returns are calculated after validating that a single daily return is available. If in the same month, the dp series can be used to find MTD, else the second to last value in the mp series is used. Same method for YTD calculation.

    opened by sfjep 5
  • PerformanceStats

    PerformanceStats ".monthly_returns" fails to work if a whole month is missing data

    Hi,

    Firstly, LOVE this package - it has been a god send to me so many thanks for your hard work and choosing to share it with us all.

    I have noticed what I believe to be a "bug" with the ".monthly_returns" when used on certain input data and with a PerformanceStats object.

    When using daily periodicity data (or intra-day) as a base input to the PerformanceStats object, if there is a whole calendar month period without a corresponding entry in the series (or more than one month in a row), the resulting data returned seems to be incorrect/incomplete.

    I have provided two csv input files and a Jupyter notebook that replicates the 2 issues I have found, with further explanation within.

    I may be missing something my end which is causing this, but I do believe it to be a legitimate "bug". ffn_bug_examples.zip

    opened by Stuj79 5
  • Yahoo changed their returned field values breaking ffn.get() for Yahoo

    Yahoo changed their returned field values breaking ffn.get() for Yahoo

    pandas-datareader 0.7.0 (released today) fixes the latest Yahoo data breakage, but Yahoo is now using new field values which breaks ffn.get(). For instance, 'Adj Close' changed to 'adjclose'. I replaced the two references to 'Adj Close' with 'adjclose' in data.py and now ffn.get() returns data, but the dataframe is only number indexed rather than date indexed. It's my first day with ffn so I'm not sure what typical behavior is, but I was just comparing my results to the examples and saw this discrepancy.

    opened by bengebre 5
  • TypeError: string indices must be integers

    TypeError: string indices must be integers

    Hi

    Today, when I was using ffn, I found that an error would be reported. After checking, it should be that the information obtained by yahoo finance has been revised. Could you please check it?

    Here is the discussion I found https://stackoverflow.com/questions/74832296/typeerror-string-indices-must-be-integers-when-getting-data-of-a-stock-from-y

    thank you very much

    opened by Allensususu 4
  • What changes when I change TRADING_DAYS_PER_YEAR ?

    What changes when I change TRADING_DAYS_PER_YEAR ?

    Hi,

    Im using bt for backtesting (great tool btw) and im exploring crypto data which trades 365 days a year. I made ffn.core. TRADING_DAYS_PER_YEAR equal to 365 and when I ran my backtests which have 5 years of daily data, I didnt see any differences in the performance stats. I assumed the annualized returns at least would change. So I have two questions...

    1. what performance metrics should change when I change TRADING_DAYS_PER_YEAR from 252 to 365?
    2. The docs say use 360 for crypto. Why would it be 360 and not 365?

    Thanks!

    opened by brettelliot 1
  • Consider consolidating with empyrical

    Consider consolidating with empyrical

    Evaluate what functionality empyrical has that ffn is missing and consider implementing as empyrical is not really maintained.

    https://github.com/quantopian/empyrical https://github.com/quantopian/empyrical/issues/125

    enhancement 
    opened by timkpaine 0
  • Sortino Ratio using Monthly Mean, not Geometric Monthly Mean

    Sortino Ratio using Monthly Mean, not Geometric Monthly Mean

    Line 2302:

    res = np.divide(er.mean(), std)

    Unless I'm reading this incorrectly, this is using the mean instead of geometric mean which is incorrect (should be .gmean(), right).

    opened by staymadson 0
  • Daily Mean Hard Coded Definition

    Daily Mean Hard Coded Definition

                self.daily_mean = r.mean() * 252
                self.daily_vol = np.std(r, ddof=1) * np.sqrt(252)
    
                # if type(self.rf) is float:
                if isinstance(self.rf, float):
                    self.daily_sharpe = r.calc_sharpe(rf=self.rf, nperiods=252)
                    self.daily_sortino = calc_sortino_ratio(r, rf=self.rf, nperiods=252)
                # rf is a price series
                else:
                    _rf_daily_price_returns = self.rf.to_returns()
                    self.daily_sharpe = r.calc_sharpe(
                        rf=_rf_daily_price_returns, nperiods=252
                    )
                    self.daily_sortino = calc_sortino_ratio(
                        r, rf=_rf_daily_price_returns, nperiods=252
                    )
    
    

    The yearly return data is hard coded to 252 days which accurately represents trading on the NYSE or other standard markets. However, other markets trade 365 (366) days per year, or somewhere in between (e.g. 6 days a week for futures). The returns should either dynamically adjust based on the time series presented or offer an ability to set the number of trading days.

    opened by staymadson 1
  • six_month calculation on monthly data

    six_month calculation on monthly data

    I used monthly data and checked the performance. I always come to the result that with "six_month" the last 7 lines are calculated. otherwise, I do not come to the same result. or am I wrong, or maybe monthly data are not suitable.

    opened by 19lex82 0
Releases(v0.3.6)
Owner
Philippe Morissette
Philippe Morissette
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
Common financial risk and performance metrics. Used by zipline and pyfolio.

empyrical Common financial risk metrics. Table of Contents Installation Usage Support Contributing Testing Installation pip install empyrical Usage S

Quantopian, Inc. 1k Dec 26, 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

null 1.8k Dec 31, 2022
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
A banking system is a group or network of institutions that provide financial services for us

A banking system is a group or network of institutions that provide financial services for us. These institutions are responsible for operating a payment system, providing loans, taking deposits, and helping with investments.

UTTKARSH PARMAR 1 Oct 24, 2021
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 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
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
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
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
Zipline, a Pythonic Algorithmic Trading Library

Zipline is a Pythonic algorithmic trading library. It is an event-driven system for backtesting. Zipline is currently used in production as the backte

Quantopian, Inc. 15.7k Jan 2, 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 2, 2023
High-performance TensorFlow library for quantitative finance.

TF Quant Finance: TensorFlow based Quant Finance Library Table of contents Introduction Installation TensorFlow training Development roadmap Examples

Google 3.5k Jan 1, 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
bt - flexible backtesting for Python

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://pmorissett

Philippe Morissette 1.6k Jan 5, 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