Andy
Andy

Reputation: 93

How can I using yfinance to get fundamental ratios ( such as P/E, P/B )

I've been wondering how can I get a series fundamentals such as P/E ratio of a company using yfinance. historical ratios for multiple company .

I have tried

import yfinance as yf
rio=yf.Ticker("RIO.AX")
rio.financials 

but my result give me the empty data frame anyone can help? or any documentation I can be able to read thanks a lot

Upvotes: 4

Views: 32949

Answers (6)

goodyonsen
goodyonsen

Reputation: 81

Instead "yfinance” I suggest "yahooquery” library for that particular purpose because “yfinance” maybe a bit troubling for retrieving what you’re looking for.

Using user15464793’s lines in his post above something like this may help:

from yahooquery import Ticker

symbol_list_yahoo = ['META', 'AAPL', 'AMZN', 'NFLX', 'GOOG']

ticker = Ticker(symbol_list_yahoo) 
fin_data_dict = ticker.financial_data
fin_data_df = pd.DataFrame.from_dict(fin_data_dict, orient=‘index’).T

There you have a nice dataframe of tickers of your choice with bunch of metrics and ratios associated.

Upvotes: 0

Usul
Usul

Reputation: 46

This is how you can use yfinance to get PE

import yfinance as yf
ticker = input("Enter a Ticker Sumbol: ")
stock_info = yf.Ticker(ticker).info
print(stock_info["trailingPE"])

if you want the forward PE its "forwardPE"

Alternatively you can calculate the PE using Price and EPS.

import yfinance as yf
ticker = input("Enter a Ticker Sumbol: ")
stock_info = yf.Ticker(ticker).info
price = stock_info["currentPrice"]
EPS = stock_info["trailingEps"]
PE = round(price / EPS, 2)
print (PE)

Upvotes: 1

user15464793
user15464793

Reputation: 149

It's a bit easier using the following lines of code. Simpler and the output yields a pandas df with trailing and forwards P/E ratios as one of the 150 values:

microsoft = yf.Ticker('MSFT')
dict =  microsoft.info
df = pd.DataFrame.from_dict(dict,orient='index')
df = df.reset_index()

outputs:

index   0
0   zip 98052-6399
1   sector  Technology
2   fullTimeEmployees   181000
3   longBusinessSummary Microsoft Corporation develops, licenses, and ...
4   city    Redmond
5   phone   425 882 8080
6   state   WA
7   country United States
8   companyOfficers []
9   website http://www.microsoft.com
10  maxAge  1
11  address1    One Microsoft Way
12  industry    Software—Infrastructure
13  ebitdaMargins   0.48649
14  profitMargins   0.38515
15  grossMargins    0.68865
16  operatingCashflow   81945001984
17  revenueGrowth   0.22
18  operatingMargins    0.42143
19  ebitda  85745000448
20  targetLowPrice  299.93
21  recommendationKey   buy
22  grossProfits    115856000000
23  freeCashflow    49819750400
24  targetMedianPrice   360
25  currentPrice    336.07
26  earningsGrowth  0.489
27  currentRatio    2.165
28  returnOnAssets  0.14589
29  numberOfAnalystOpinions 38
30  targetMeanPrice 357.27
31  debtToEquity    51.938
32  returnOnEquity  0.49303
33  targetHighPrice 407
34  totalCash   130584002560
35  totalDebt   78934999040
36  totalRevenue    176250994688
37  totalCashPerShare   17.393
38  financialCurrency   USD
39  revenuePerShare 23.395
40  quickRatio  1.961
41  recommendationMean  1.6
42  exchange    NMS
43  shortName   Microsoft Corporation
44  longName    Microsoft Corporation
45  exchangeTimezoneName    America/New_York
46  exchangeTimezoneShortName   EST
47  isEsgPopulated  False
48  gmtOffSetMilliseconds   -18000000
49  quoteType   EQUITY
50  symbol  MSFT
51  messageBoardId  finmb_21835
52  market  us_market
53  annualHoldingsTurnover  None
54  enterpriseToRevenue 14.051
55  beta3Year   None
56  enterpriseToEbitda  28.881
57  52WeekChange    0.550062
58  morningStarRiskRating   None
59  forwardEps  10.51
60  revenueQuarterlyGrowth  None
61  sharesOutstanding   7507979776
62  fundInceptionDate   None
63  annualReportExpenseRatio    None
64  totalAssets None
65  bookValue   20.242
66  sharesShort 49332744
67  sharesPercentSharesOut  0.0066
68  fundFamily  None
69  lastFiscalYearEnd   1625011200
70  heldPercentInstitutions 0.71896
71  netIncomeToCommon   67882999808
72  trailingEps 8.939
73  lastDividendValue   0.56
74  SandP52WeekChange   0.29114
75  priceToBook 16.6026
76  heldPercentInsiders 0.00078
77  nextFiscalYearEnd   1688083200
78  yield   None
79  mostRecentQuarter   1632960000
80  shortRatio  1.97
81  sharesShortPreviousMonthDate    1632960000
82  floatShares 7500172144
83  beta    0.862337
84  enterpriseValue 2476438192128
85  priceHint   2
86  threeYearAverageReturn  None
87  lastSplitDate   1045526400
88  lastSplitFactor 2:1
89  legalType   None
90  lastDividendDate    1629244800
91  morningStarOverallRating    None
92  earningsQuarterlyGrowth 0.476
93  priceToSalesTrailing12Months    14.316
94  dateShortInterest   1635465600
95  pegRatio    2.25
96  ytdReturn   None
97  forwardPE   31.9762
98  lastCapGain None
99  shortPercentOfFloat 0.0066
100 sharesShortPriorMonth   47171313
101 impliedSharesOutstanding    None
102 category    None
103 fiveYearAverageReturn   None
104 previousClose   336.72
105 regularMarketOpen   337.54
106 twoHundredDayAverage    284.087
107 trailingAnnualDividendYield 0.0068306
108 payoutRatio 0.2506
109 volume24Hr  None
110 regularMarketDayHigh    337.842
111 navPrice    None
112 averageDailyVolume10Day 21823516
113 regularMarketPreviousClose  336.72
114 fiftyDayAverage 310.283
115 trailingAnnualDividendRate  2.3
116 open    337.54
117 toCurrency  None
118 averageVolume10days 21823516
119 expireDate  None
120 algorithm   None
121 dividendRate    2.48
122 exDividendDate  1637107200
123 circulatingSupply   None
124 startDate   None
125 regularMarketDayLow 334.034
126 currency    USD
127 trailingPE  37.5959
128 regularMarketVolume 15975249
129 lastMarket  None
130 maxSupply   None
131 openInterest    None
132 marketCap   2523206778880
133 volumeAllCurrencies None
134 strikePrice None
135 averageVolume   23879857
136 dayLow  334.034
137 ask 336.4
138 askSize 800
139 volume  15975249
140 fiftyTwoWeekHigh    338.79
141 fromCurrency    None
142 fiveYearAvgDividendYield    1.45
143 fiftyTwoWeekLow 208.16
144 bid 336.32
145 tradeable   False
146 dividendYield   0.0074
147 bidSize 900
148 dayHigh 337.842
149 regularMarketPrice  336.07
150 preMarketPrice  337.5
151 logo_url    https://logo.clearbit.com/microsoft.com

Upvotes: 6

Maexel
Maexel

Reputation: 94

There are two lines of code that have to be inserted to retrieve financials, balance sheet and cashflow statements again.

The solution was found by afju where he/she has posted it in the comments section with a short explanation: https://aroussi.com/post/python-yahoo-finance
so credits to him/her

Here is what you need to change in
.../site-packages/yfinance/base.py
which has worked for me for following version of yfinance:

import yfinance as yf
yf.__version__
>>>'0.1.54'

insert comment in # get fundamentals (around line 375):

#data = utils.get_json(url+'/financials', proxy)

and write these two lines:

url = "{}/{}/financials".format(self._scrape_url, self.ticker)
data = utils.get_json(url, proxy)

so in the end, it looks like this:

# get fundamentals
#data = utils.get_json(url+'/financials', proxy)
url = "{}/{}/financials".format(self._scrape_url, self.ticker)
data = utils.get_json(url, proxy)

Upvotes: 3

redspidermkv
redspidermkv

Reputation: 541

yfinance seems to no longer be able to retrieve company financials (it hasn't been working for me since October 2020)

However, if you're not averse to trying out another library, there's yahoo_fin

pip install yahoo_fin
pip install requests_html

Once installed:

import yahoo_fin.stock_info as si
msft_data = si.get_quote_table("MSFT")

The dictionary looks like the following:

{'1y Target Est': 239.71,
 '52 Week Range': '132.52 - 232.86',
 'Ask': '215.25 x 800',
 'Avg. Volume': 31253650.0,
 'Beta (5Y Monthly)': 0.87,
 'Bid': '215.00 x 900',
 "Day's Range": '214.04 - 216.27',
 'EPS (TTM)': 6.2,
 'Earnings Date': 'Jan 27, 2021 - Feb 01, 2021',
 'Ex-Dividend Date': 'Nov 18, 2020',
 'Forward Dividend & Yield': '2.24 (1.04%)',
 'Market Cap': '1.627T',
 'Open': 214.85,
 'PE Ratio (TTM)': 34.72,
 'Previous Close': 213.87,
 'Quote Price': 215.22999572753906,
 'Volume': 12886232.0}

The trailing 12 month PE ratio is there, the P/B ratio isn't available via this library.

Disclaimer: I have no affiliation with the mentioned library, I've just found it a useful alternative to yfinance when yfinance doesn't work.

More info can be found at this link: https://algotrading101.com/learn/yahoo-finance-api-guide/

Upvotes: 7

Merv Merzoug
Merv Merzoug

Reputation: 1237

You might want to try google in the future to find docs for python packages. Here is the link to this package's documentation.

https://pypi.org/project/yfinance/

Upvotes: -2

Related Questions