Djerun
Djerun

Reputation: 37

Downloading financial ratios for tickers in a dataframe with Python library FundamenalAnalysis

I try to download key financial ratios from Yahoo Finance via the FundamentalAnalysis library. It's pretty easy for a single ticker.

Tickers in a dataframe

I have a dataframe with tickers and company names like this:

  Ticker                      Company
0      A    Agilent Technologies Inc.
1     AA            ALCOA CORPORATION
2    AAC             AAC Holdings Inc
3    AAL  AMERICAN AIRLINES GROUP INC
4   AAME      Atlantic American Corp.

Loop over dataframe does not work

I tried to use a for-loop to download the ratios for every ticker with fa.ratios() from FundamentalAnalysis.

for i in range (3):
    i = 0
    i = i + 1
    Ratios = fa.ratios(tickers["Ticker"][i])

This loop shall download all ratios: First for one ticker, then the second, and so on.

I also tried to change the dataframe into a list, but it didn't work as well.

A manual typed list works

If I put them in a list manually like:

Symbol = ["TSLA" , "AAPL" , "MSFT"]

it works somehow.

But as I want to work with data from 1000+ tickers I don't want to type all of them manually into a list.

Maybe this question has already been answered elsewhere. In that case sorry. But I've not been able to find a thread that helps me.

Question

How can I iterate over the ticker-names in the dataframe?

Upvotes: -1

Views: 369

Answers (1)

furas
furas

Reputation: 142985

You can get symbols using

symbols = df['Ticker'].to_list()

and then you could use for-loop without range()

ratios = dict()

for s in symbols:
    ratios[s] = fa.ratios(s)

print(ratios)

Because some symbols may not give ratios so you should use try/except


Minimal working example. I use io.StringIO only to simulate file.

import FundamentalAnalysis as fa
import pandas as pd
import io

text='''Ticker                      Company
A    Agilent Technologies Inc.
AA            ALCOA CORPORATION
AAC             AAC Holdings Inc
AAL  AMERICAN AIRLINES GROUP INC
AAME      Atlantic American Corp.'''

df = pd.read_csv(io.StringIO(text), sep='\s{2,}')

symbols = df['Ticker'].to_list()
#symbols = ["TSLA" , "AAPL" , "MSFT"]
print(symbols)

ratios = dict()
for s in symbols:
    try:
        ratios[s] = fa.ratios(s)
    except Exception as ex:
        print(s, ex)

for s, ratio in ratios.items():
    print(s, ratio)

EDIT: it seems fa.ratios() returns DataFrames and if you will keep them on list then you can concatenate all DataFrames to one DataFrame

ratios = list()  # list instead of dictionary
for s in symbols:
    try:
        ratios.append(fa.ratios(s))  # append to list
    except Exception as ex:
        print(s, ex)

df = pd.concat(ratios, axis=1)  # convert list of DataFrames to one DataFrame

print(df.columns)
print(df)

Doc: pandas.concat()

Upvotes: 1

Related Questions