ffn - a financial function library for Python

Related tags

Financeffn
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)
Fourth and final milestone project

Milestone Project 4: Pound Dog Click link to visit "Pound Dog" Aim of the project The aim of this project is to provide access to a website informing

Jamie Wilson 1 Oct 31, 2021
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
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

8 Dec 13, 2022
stock data on eink with raspberry

small python skript to display tradegate data on a waveshare e-ink important you need locale "de_AT.UTF-8 UTF-8" installed. do so in raspi-config's Lo

Simon Oberhammer 24 Feb 22, 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
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 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

UTTKARSH PARMAR 1 Oct 24, 2021
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
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
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
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
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
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
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
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 05, 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
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 01, 2023
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 05, 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 01, 2023