Python Stock Screener!
Before we get into the code, we need some criteria:
- Find the stock list from a CSV
- Which stocks pay dividends?
- Get company description
- Save all CSV into one
Find the stock list from a CSV
First we need to create our CSV to get the tickets (stocks symbols):
symbol shortName exchange type rank
AMC AMC Entertainment Holdings, Inc NYQ equity 2831691
TSLA Tesla, Inc. NMS equity 2487570
WISH ContextLogic Inc. NMS equity 1148497
GME GameStop Corporation NYQ equity 1083789
AAPL Apple Inc. NMS equity 972582
CLOV Clover Health Investments, Corp NMS equity 862224
PLTR Palantir Technologies Inc. NYQ equity 780624
TRCH Torchlight Energy Resources, In NCM equity 755951
NIO NIO Inc. NYQ equity 751163
BB BlackBerry Limited NYQ equity 706585
AMZN Amazon.com, Inc. NMS equity 662314
SNDL Sundial Growers Inc. NCM equity 635827
NVDA NVIDIA Corporation NMS equity 588359
MSFT Microsoft Corporation NMS equity 564667
PLUG Plug Power, Inc. NCM equity 522786
FNMA FEDERAL NATIONAL MORTGAGE ASSOC PNK equity 505031
F Ford Motor Company NYQ equity 499922
TTD The Trade Desk, Inc. NGM equity 487787
NVAX Novavax, Inc. NMS equity 473908
Here we will work with the file, we need to read the file and get it into a dictionary (df)
import pandas as pd
from pathlib import Path# Get file from home path
homePath = str(Path.home())#Choose the path that you file is
df = pd.read_csv( homePath + "/genericStock.csv")
#From read file get values from column symbol
tickers = set(df['symbol'].values)
#Show all found tickers
print(tickers)
Where homePath is the path where you file is. After it you can see all the tickets
{'PLUG', 'TSLA', 'AAPL', 'NVDA', 'AMC', 'PLTR', 'MSFT', 'SNDL', 'CLOV', 'NVAX', 'F', 'GME', 'AMZN', 'TRCH', 'BB', 'FNMA', 'WISH', 'NIO', 'TTD'}
Which stocks pay dividends?
To do it we will install the library called yahoo_fin
pip install yahoo_fin
It’s helps to scrape the stock data.
To understand how it’s works, we go to Yahoo! Finance, and search for example, AAPPL
As we can see there’s some information about the company, now go to Statistics, scroll down and we can see the information that we use for our criteria.
Now we can do it in code like this
import pandas as pd
from pathlib import Path
import yahoo_fin.stock_info as si #pip install yahoo_fin# Get file from home path
homePath = str(Path.home())#Choose the path that you file is
df = pd.read_csv( homePath + "/genericStock.csv")
#From read file get values from column symbol
tickers = set(df['symbol'].values)#In all tickers
for ticker in tickers:
# Get all stats
stats = si.get_stats(ticker)
print(stats)
In this example it’s will show all tickers stats.
We wanna know where to get the dividend yield in this dictionary, example
stats = si.get_stats('AAPL')
print(stats)
Here I show only AAPL stats
Attribute Value
0 Beta (5Y Monthly) 1.21
1 52-Week Change 3 47.50%
2 S&P500 52-Week Change 3 39.74%
3 52 Week High 3 145.09
4 52 Week Low 3 87.82
5 50-Day Moving Average 3 127.51
6 200-Day Moving Average 3 128.74
7 Avg Vol (3 month) 3 84.54M
8 Avg Vol (10 day) 3 82.94M
9 Shares Outstanding 5 16.69B
10 Implied Shares Outstanding 6 NaN
11 Float 16.67B
12 % Held by Insiders 1 0.07%
13 % Held by Institutions 1 58.70%
14 Shares Short (Jun 14, 2021) 4 108.94M
15 Short Ratio (Jun 14, 2021) 4 1.52
16 Short % of Float (Jun 14, 2021) 4 0.65%
17 Short % of Shares Outstanding (Jun 14, 2021) 4 0.65%
18 Shares Short (prior month May 13, 2021) 4 94.75M
19 Forward Annual Dividend Rate 4 0.88
20 Forward Annual Dividend Yield 4 0.66%
21 Trailing Annual Dividend Rate 3 0.82
22 Trailing Annual Dividend Yield 3 0.61%
23 5 Year Average Dividend Yield 4 1.34
24 Payout Ratio 4 18.34%
25 Dividend Date 3 May 12, 2021
26 Ex-Dividend Date 4 May 06, 2021
27 Last Split Factor 2 4:1
28 Last Split Date 3 Aug 30, 2020
29 Fiscal Year Ends Sep 25, 2020
30 Most Recent Quarter (mrq) Mar 26, 2021
31 Profit Margin 23.45%
32 Operating Margin (ttm) 27.32%
33 Return on Assets (ttm) 16.90%
34 Return on Equity (ttm) 103.40%
35 Revenue (ttm) 325.41B
36 Revenue Per Share (ttm) 19.14
37 Quarterly Revenue Growth (yoy) 53.60%
38 Gross Profit (ttm) 104.96B
39 EBITDA 99.82B
40 Net Income Avi to Common (ttm) 76.31B
41 Diluted EPS (ttm) 4.45
42 Quarterly Earnings Growth (yoy) 110.10%
43 Total Cash (mrq) 69.83B
44 Total Cash Per Share (mrq) 4.18
45 Total Debt (mrq) 134.74B
46 Total Debt/Equity (mrq) 194.78
47 Current Ratio (mrq) 1.14
48 Book Value Per Share (mrq) 4.15
49 Operating Cash Flow (ttm) 99.59B
50 Levered Free Cash Flow (ttm) 80.12B
We can see the index number and columns Attribute and Value, lets get the Value from index 22
# Get all stats
stats = si.get_stats('AAPL')
#Value
values = stats['Value']
#From index 22
dy = values.iloc[22]
#To float
dy = float(dy.replace('%', ''))
print(dy)
At his point our code will look like this
import pandas as pd
from pathlib import Path
import yahoo_fin.stock_info as si #pip install yahoo_fin# Get file from home path
homePath = str(Path.home())#Choose the path that you file is
df = pd.read_csv( homePath + "/genericStock.csv")
#From read file get values from column symbol
tickers = set(df['symbol'].values)#In all tickers
for ticker in tickers:
# Get all stats
stats = si.get_stats(ticker)
#Value
values = stats['Value']
#From index 22
dy = values.iloc[22]
#To float
dy = float(dy.replace('%', ''))
print(dy)
So, get only the stocks that’s dy > 0 , and write in a CSV
if dy > 0:
data = {
'Ticker': ticker,
'DY': dy
}
dfTicker = pd.DataFrame(data, index=[0])
dfTicker.to_csv(f'{ticker}.csv')
After run the code we can see some created CSV files in the working directory. If you open one will look like following
,Ticker,DY
0,AAPL,0.61
Get company description
To find company description we can see it in Profile on Yahoo! Finance
But how to get this? Using another lib called yfinance
pip install yfinance
Change the code adding this
import yfinance as yf
And change the code to this
#Get stocks with dy
if dy > 0:
#Get stock description
info = yf.Ticker(ticker).info
description = info['longBusinessSummary']
#Populate data
data = {
'Ticker': ticker,
'DY': dy,
'Description': description
}
dfTicker = pd.DataFrame(data, index=[0])
#Write to csv
dfTicker.to_csv(f'{ticker}.csv')
And your CSV’s files will have the following information
,Ticker,DY,Description
0,AAPL,0.61,"Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. It also sells various related services. The company offers iPhone, a line of smartphones; Mac, a line of personal computers; iPad, a line of multi-purpose tablets; and wearables, home, and accessories comprising AirPods, Apple TV, Apple Watch, Beats products, HomePod, iPod touch, and other Apple-branded and third-party accessories. It also provides AppleCare support services; cloud services store services; and operates various platforms, including the App Store, that allow customers to discover and download applications and digital content, such as books, music, video, games, and podcasts. In addition, the company offers various services, such as Apple Arcade, a game subscription service; Apple Music, which offers users a curated listening experience with on-demand radio stations; Apple News+, a subscription news and magazine service; Apple TV+, which offers exclusive original content; Apple Card, a co-branded credit card; and Apple Pay, a cashless payment service, as well as licenses its intellectual property. The company serves consumers, and small and mid-sized businesses; and the education, enterprise, and government markets. It sells and delivers third-party applications for its products through the App Store. The company also sells its products through its retail and online stores, and direct sales force; and third-party cellular network carriers, wholesalers, retailers, and resellers. Apple Inc. was founded in 1977 and is headquartered in Cupertino, California."
Save all CSV into one
Here we will join all CSV files into one
Our code look like it
import pandas as pd
from pathlib import Path
import yahoo_fin.stock_info as si #pip install yahoo_fin
import yfinance as yf# Get file from home path
homePath = str(Path.home())#Choose the path that you file is
df = pd.read_csv( homePath + "/genericStock.csv")
#From read file get values from column symbol
tickers = set(df['symbol'].values)#In all tickers
for ticker in tickers:
# Get all stats
stats = si.get_stats(ticker)
#Value
values = stats['Value']
#From index 22
dy = values.iloc[22]
#To float
dy = float(dy.replace('%', ''))
#Get stocks with dy
if dy > 0:
#Get stock description
info = yf.Ticker(ticker).info
description = info['longBusinessSummary']
#Populate data
data = {
'Ticker': ticker,
'DY': dy,
'Description': description
}
dfTicker = pd.DataFrame(data, index=[0])
#Write to csv
dfTicker.to_csv(f'{ticker}.csv')
Let’s add some piece of code.
import glob
import os
We need some OS permissions to see the files.
After that let’s change our code, to concatenate the .csv files
# Get all files from current dir, which ends with .csv
all_files = glob.glob(os.path.join('.', "*.csv"))
df_from_each_file = []
for f in all_files:
df_from_each_file.append(pd.read_csv(f, sep=',', error_bad_lines=False))# Concat all files
df_merged = pd.concat(df_from_each_file, ignore_index=True)
# Replace index with Ticker
df_merged.set_index('Ticker', inplace = True)
# Merge into one csv, change to directory you want to save
df_merged.to_csv('stocksScreened.csv')
#After it we can remove all stocks files
for f in all_files:
if not str(f).endswith('stocksScreened.csv'):
os.remove(f)
After run it we found the following file in current directory
Ticker,DY,Description
MSFT,0.82,"Microsoft ···"
NVDA,0.08,"NVIDIA Corporation ···"
AMC,0.05,"AMC Entertainment ···"
AAPL,0.61,"Apple Inc. ···"
And there’s our final code
import pandas as pd
from pathlib import Path
import yahoo_fin.stock_info as si #pip install yahoo_fin
import yfinance as yf
import glob
import os# Get file from home path
homePath = str(Path.home())#Choose the path that you file is
df = pd.read_csv( homePath + "/genericStock.csv")
#From read file get values from column symbol
tickers = set(df['symbol'].values)#In all tickers
for ticker in tickers:
# Get all stats
stats = si.get_stats(ticker)
#Value
values = stats['Value']
#From index 22
dy = values.iloc[22]
#To float
dy = float(str(dy).replace('%', ''))
#Get stocks with dy
if dy > 0:
#Get stock description
info = yf.Ticker(ticker).info
description = info['longBusinessSummary']
#Populate data
data = {
'Ticker': ticker,
'DY': dy,
'Description': description
}
dfTicker = pd.DataFrame(data, index=[0])
# Replace index with Ticker
dfTicker.set_index('Ticker', inplace = True)
#Write to csv
dfTicker.to_csv(f'{ticker}.csv')# Get all files from current dir, which ends with .csv
all_files = glob.glob(os.path.join('.', "*.csv"))
df_from_each_file = []
for f in all_files:
df_from_each_file.append(pd.read_csv(f, sep=',', error_bad_lines=False))# Concat all files
df_merged = pd.concat(df_from_each_file, ignore_index=True)
# Replace index with Ticker
df_merged.set_index('Ticker', inplace = True)
# Merge into one csv, change to directory you want to save
df_merged.to_csv('stocksScreened.csv')
#After it we can remove all stocks files
for f in all_files:
if not str(f).endswith('stocksScreened.csv'):
os.remove(f)
And we finish this! Please feel free to modify, leave a feedback or asks questions!