Lo-Fi Python

Jan 16, 2021

Pick Stocks Intelligently with ffn

How do you calculate stock valuation metrics like Sharpe ratio. Recently I've been reading about common stock valuation metrics and wondered how I can apply them to my stock portfolio. I started reading about different metrics, sketching formulas and entertained writing a script to calculate these metrics. But Python has no shortage of finance-related libraries. After some furious googling I found ffn, a way better option than rolling my own formulas. It's a "financial function" library, installable with pip.

It will be interesting to observe how these metrics vary in my portfolio and learn more of ffn's API. I like that they use pandas dataframes within their library because I'm already familiar with them. At minimum, it's good to understand what stock formulas purport to measure and what it means if the measure is low or high. It makes sense to compare stocks in similar industries or competitors like NKE and ADDYY. This is a neat tool for stock nerds who want to level up their stock analysis, make smart decisions and ideally pad the portfolio!

The funny thing is... my lowest university grade was a "C" in my only Finance class. It wasn't easy for me to grasp. But with Python it's a little more interesting and easier to apply. Anyone can level up their finance skills thanks to a cornucopia of finance calculation libraries in the Python ecosystem.

Recommended Reading: A Brief Introduction - ffn documentation

Install ffn with pip:

python -m pip install ffn

Here's the code to get stock data with ffn:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import ffn

# ffn.get returns a pandas dataframe of market data.
data = ffn.get(
    'tsla,spot,nflx,nke,addyy',
    start='2019-01-01',
    end='2020-12-31'
)
print(data.head())
stats = data.calc_stats()
print(stats.display())
ffn stock report 2019-2021

side note on the pyfolio library

I first considered using pyfolio to pull stock data. It is not "out of the box" ready per se to deliver the results pictured in their "single stock" example documentation. You'd need to find another way to fetch your market data or somehow patch the Yahoo Finance API within pyfolio. I preferred ffn, mostly because it worked right away after pip installing it and running the above code.

2024 Update

For a capable finance module, I recommend yfinance. It has worked well for me also. ffn and pyfolio both depend on the Yahoo Finance API, which tends to change and break these libraries. Troubleshooting traceback errors may be required.

Try these other Python financial analysis libraries:

Best Python Libraries/Packages for Finance and Financial Data Scientists

python's built-in statistics module - Backtrader

tia: Toolkit for integration and analysis - FinTA (Financial Technical Analysis)

pandas-datareader - mplfinance - PyPortfolioOpt - TA-Lib Python Port

finsou.py (CLI written by me)

awesome-quant