Top Best/Worst Performing Stocks with Python

Just 13 lines of code, I promise

First, we need to define the stocks we wanna watch:

tickers = ['voo', 'msft', 'googl', 'fb', 'tsla', 'aapl', 'nflx', 'twtr']

Then let's use Python's ffn library to get the closing prices of the last three trading sessions (three because we might be on a weekend):

start_date = datetime.date.today() - datetime.timedelta(days=3)
prices = ffn.get(tickers, start=start_date)

Once we have the prices, let's calculate the percentual change over the days, remove any n/a values and get the last price diff using iloc[-1:]:

final = prices.pct_change().dropna().iloc[-1:].T.reset_index()
final.columns = ['ticker', 'pct']

We also need to transpose the data frame and reset the index before advancing to the final step:

best = final.nlargest(5, 'pct')
worst = final.nsmallest(5, 'pct')

Here we get the top 5 best and worst performing stocks over the last trading session.

print(best)
#   ticker       pct
# 3     fb  0.041239
# 6   nflx  0.014640
# 2  googl  0.002780
# 4   tsla  0.002618
# 1   msft -0.001604

print(worst)
#   ticker       pct
# 7   twtr -0.007344
# 5   aapl -0.004480
# 0    voo -0.001778
# 1   msft -0.001604
# 4   tsla  0.002618

Putting all together now:

import ffn
import datetime

tickers = ['voo', 'msft', 'googl', 'fb', 'tsla', 'aapl', 'nflx', 'twtr']

start_date = datetime.date.today() - datetime.timedelta(days=3)
prices = ffn.get(tickers, start=start_date)

final = prices.pct_change().dropna().iloc[-1:].T.reset_index()
final.columns = ['ticker', 'pct']

best = final.nlargest(5, 'pct')
worst = final.nsmallest(5, 'pct')

Hope you have liked :)

Written on March 20, 2021

Share: