yfinance is a Python api to the Yahoo! finance site.
This file resides at /c/cs458/www/lectures/yfinance.ipynb
The fundamental law of finance is:
Buy low, sell high.
But what do you buy? When they think of finance and investing, most people think about the Dow Jones Industrial Average, which comprises 30 large cap US stocks, traded on the New York Stock Exchange (NYSE) and the NASDAQ exchange. (A large cap stock has a market capitalization greater than $10 billion. The market cap is simply the price of a share of stock times the number of shares outstanding.)
By owning a share of stock, you become an owner of the company. You have an equity stake in running the company. Major decisions by the company are ratified by a shareholder vote. If you own more than 50% of the stock in a company, you control the company. Stock is also known as equity which is just one asset class in which you might choose to invest. Others include bonds (aka, fixed income or debt), real estate, commodities (e.g., wheat, oil, gold), foreign exchance (currency, like dollars, euros, and yen), derivatives (such as mortgage back securities), and infrastructure (such as roads and airports).
We are going to focus on equity, that is, stocks. The yfinance Python module provides a boatload of information about US stocks and other securities.
As we learned from Tversky and Kahnemann and behavioral economists, people are risk averse. They don't like losing money. In 1952, Harry Markowitz came up with Modern Portfolio Theory which, among other things, showed how you can construct a collection or portfolio of stocks to reduce or even minimize the risk of the overall investment. One of Markowitz's insights was that the volatility of a stock's price was a suitable measure of the risk of the investment. You can reduce the overall volatility of a portfolio by investing stocks that are not correlated with each other. Thus, one stock may go up with inflation and another might go down. These movements can offset each other and reduce the portfolio's volatility or risk.
You can fully diversify your portfolio by holding 30 or so stocks - assuming that they are not correlated. One hundred years ago, investors thought they were diversified if they owned 20 different railroad stocks. Go figure.
These days we measure volatility of the entire stock market with the volatility index or VIX. It is also known as the fear index or fear gauge. The higher the VIX, the riskier the market. A rule of thumb is if the VIX is below 14, the market is not risky.
We assume that everyone wants to avoid losing money. However, there are many different ways to make money. Many stocks pay dividends (usually quarterly) which can provide income to the investor. Usually companies that pay dividends are older and more stable and established, such as banks and utilities. These stocks are often called value stocks.
Many stocks do not pay dividends. Instead they reinvest that money in the company to help it grow and expand. These stocks are often called growth stocks.
Usually, growth stocks are more volatile than value stocks, which is to say that they are more risky.
These categories are not always clear cut.
Another metric that relates to MPT, is beta, a measure of a stock's volatility relative to the market as a whole. A beta of 1 means that the stock has the same volatility as the entire market (usually the S and P 500). A stable stock will have a beta below 1. A risky stock will have a beta over 1.
To diversify the risk in a portfolio, you need to buy stocks with different volatility patterns. One common way to do this is by investing in different sectors or industries.
Different sectors respond differently to market conditions. In recent years, technology has outperformed sectors like materials or real estate. However, there is no clear pattern over time.
Many Wall Street firms, like Morgan Stanley, Goldman Sachs, and Merrill Lynch, employ finance professionals who advise investors which stocks to buy and sell. For example, see a recent Merrill Lynch report on Apple (AAPL). An analysis will usually assign a recommendation of buy, sell, or hold, as well as a price target or price objective - their prediction of the price within the next 12 months. Merrill Lynch assigns Apple a NEUTRAL rating and a price objective of 158 from the current price of 151. This is pretty bullish. Note that Merrill Lynch also reports an ESGMeter score of high for Apple. ESG stands for Environmant, Social, and Governance which measures a company's commitment to climate change, diversity and related initiatives. The hope is that a company can do well by doing good. According to Merrill Lynch, Apple is one of the good guys.
One focus of a security analyst is to predict future earnings. This figure becomes
part of price/earnings ratio or simply p/e ratio. A low PE suggest that the stock is cheap. A high PE suggests that the stock is expensive.
However, the PE ratio varies considerably across industries.
Also, there are quantitative models that can value a stock based on future earnings or discounted cash flows (DCF). This approach can be used on other assets in addition to stock. A security analyst can project company earnings and then plug those numbers into a DCF model to get a valuation for the company. Using earnings per share, the valuation is the estimated current price of the company. If that price is higher than the market price, then the stock is a BUY. If the valuation price is lower than the market price, the stock is a SELL.
In the homework, you are to write some code that could replace a security analyst.
In addition to analyzing companies, Merrill Lynch also provides sample model portfolios, namely:
Each of these portfolios comprise 30 or so individual stocks across a dozen industrial sectors. The portfolio specifies the weightings of each holding. Every few weeks or months, Merrill Lynch will publish changes to weightings or holdings to recalibrate the portfolio. See the Research Portfolio Holdings:MLHoldings.pdf
Merrill Lynch publishes a primer which explains the investment philosophy and process used to construct these portfolios. The basic premise is that each portfolio has its own risk profile, with Large Cap Defensive being safer than Income, and so forth. Here is last month's Research Portfolio Primer: MLPrimer.pdf
As a machine learning exercise, you could use the holdings of these portfolios as training data to learn the properties of an income stock versus a growth stock.
We get started by loading yfinance and some other useful modules. These are available on the zoo. If you do not have them on you personal machine, you can probably install them with
pip install
import pandas as pd
import yfinance as yf
import numpy
numpy.version.version
'1.22.0'
yf.version.version
'0.2.9'
from yahoofinancials import YahooFinancials
aapl_df = yf.download('AAPL',
start='2019-01-01',
end='2023-02-03',
progress=False,
)
aapl_df.head()
Open | High | Low | Close | Adj Close | Volume | |
---|---|---|---|---|---|---|
Date | ||||||
2019-01-02 00:00:00-05:00 | 38.722500 | 39.712502 | 38.557499 | 39.480000 | 38.105148 | 148158800 |
2019-01-03 00:00:00-05:00 | 35.994999 | 36.430000 | 35.500000 | 35.547501 | 34.309597 | 365248800 |
2019-01-04 00:00:00-05:00 | 36.132500 | 37.137501 | 35.950001 | 37.064999 | 35.774239 | 234428400 |
2019-01-07 00:00:00-05:00 | 37.174999 | 37.207500 | 36.474998 | 36.982498 | 35.694614 | 219111200 |
2019-01-08 00:00:00-05:00 | 37.389999 | 37.955002 | 37.130001 | 37.687500 | 36.375065 | 164101200 |
aapl_df.tail()
Open | High | Low | Close | Adj Close | Volume | |
---|---|---|---|---|---|---|
Date | ||||||
2023-01-27 00:00:00-05:00 | 143.160004 | 147.229996 | 143.080002 | 145.929993 | 145.929993 | 70492800 |
2023-01-30 00:00:00-05:00 | 144.960007 | 145.550003 | 142.850006 | 143.000000 | 143.000000 | 64015300 |
2023-01-31 00:00:00-05:00 | 142.699997 | 144.339996 | 142.279999 | 144.289993 | 144.289993 | 65874500 |
2023-02-01 00:00:00-05:00 | 143.970001 | 146.610001 | 141.320007 | 145.429993 | 145.429993 | 77663600 |
2023-02-02 00:00:00-05:00 | 148.899994 | 151.179993 | 148.169998 | 150.820007 | 150.820007 | 118339000 |
aapl_df = yf.download('AAPL')
[*********************100%***********************] 1 of 1 completed
import matplotlib
ticker = yf.Ticker('AAPL')
aapl_df = ticker.history(period="5y")
aapl_df['Close'].plot(title="APPLE's stock price")
<AxesSubplot: title={'center': "APPLE's stock price"}, xlabel='Date'>
dir(ticker)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_analysis', '_base_url', '_data', '_download_options', '_earnings', '_earnings_dates', '_expirations', '_fast_info', '_fetch_ticker_tz', '_financials', '_fix_unit_mixups', '_fix_zeroes', '_fundamentals', '_get_ticker_tz', '_history', '_history_metadata', '_holders', '_isin', '_news', '_options2df', '_quote', '_reconstruct_intervals_batch', '_scrape_url', '_shares', '_tz', 'actions', 'analyst_price_target', 'balance_sheet', 'balancesheet', 'basic_info', 'calendar', 'capital_gains', 'cash_flow', 'cashflow', 'dividends', 'earnings', 'earnings_dates', 'earnings_forecasts', 'earnings_trend', 'fast_info', 'financials', 'get_actions', 'get_analyst_price_target', 'get_balance_sheet', 'get_balancesheet', 'get_calendar', 'get_capital_gains', 'get_cash_flow', 'get_cashflow', 'get_dividends', 'get_earnings', 'get_earnings_dates', 'get_earnings_forecast', 'get_earnings_trend', 'get_financials', 'get_history_metadata', 'get_income_stmt', 'get_incomestmt', 'get_info', 'get_institutional_holders', 'get_isin', 'get_major_holders', 'get_mutualfund_holders', 'get_news', 'get_recommendations', 'get_recommendations_summary', 'get_rev_forecast', 'get_shares', 'get_shares_full', 'get_splits', 'get_sustainability', 'get_trend_details', 'history', 'history_metadata', 'income_stmt', 'incomestmt', 'info', 'institutional_holders', 'isin', 'major_holders', 'market_cap', 'mutualfund_holders', 'news', 'option_chain', 'options', 'quarterly_balance_sheet', 'quarterly_balancesheet', 'quarterly_cash_flow', 'quarterly_cashflow', 'quarterly_earnings', 'quarterly_financials', 'quarterly_income_stmt', 'quarterly_incomestmt', 'recommendations', 'recommendations_summary', 'revenue_forecasts', 'session', 'shares', 'splits', 'stats', 'sustainability', 'ticker']
for k,v in ticker.info.items():
print (k, '\t', v, '\n')
zip 95014 sector Technology fullTimeEmployees 164000 longBusinessSummary Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. It also sells various related services. In addition, 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, and HomePod. Further, it provides AppleCare support and 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. Additionally, the company offers various services, such as Apple Arcade, a game subscription service; Apple Fitness+, a personalized fitness 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 distributes 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 incorporated in 1977 and is headquartered in Cupertino, California. city Cupertino phone 408 996 1010 state CA country United States companyOfficers [] website https://www.apple.com maxAge 1 address1 One Apple Park Way industry Consumer Electronics ebitdaMargins 0.32329 profitMargins 0.24558 grossMargins 0.43058997 operatingCashflow 109189996544 revenueGrowth -0.055 operatingMargins 0.29408002 ebitda 125287997440 targetLowPrice 118 recommendationKey buy grossProfits 170782000000 freeCashflow 84729126912 targetMedianPrice 171.5 earningsGrowth -0.105 currentRatio 0.938 returnOnAssets 0.19569999 numberOfAnalystOpinions 38 targetMeanPrice 168.9 debtToEquity 195.868 returnOnEquity 1.47943 targetHighPrice 210 totalCash 51355000832 totalDebt 111109996544 totalRevenue 387537010688 totalCashPerShare 3.246 financialCurrency USD revenuePerShare 24.084 quickRatio 0.769 recommendationMean 2 shortName Apple Inc. longName Apple Inc. isEsgPopulated False gmtOffSetMilliseconds -18000000 quoteType EQUITY messageBoardId finmb_24937 market us_market annualHoldingsTurnover None enterpriseToRevenue 6.462 beta3Year None enterpriseToEbitda 19.988 52WeekChange -0.099965036 morningStarRiskRating None forwardEps 6.61 revenueQuarterlyGrowth None sharesOutstanding 15821899776 fundInceptionDate None annualReportExpenseRatio None totalAssets None bookValue 3.581 sharesShort 121868919 sharesPercentSharesOut 0.0077 fundFamily None lastFiscalYearEnd 1663977600 heldPercentInstitutions 0.61239 netIncomeToCommon 95171002368 trailingEps 5.89 lastDividendValue 0.23 SandP52WeekChange -0.07747549 priceToBook 42.58587 heldPercentInsiders 0.00072999997 nextFiscalYearEnd 1695513600 yield None mostRecentQuarter 1672444800 shortRatio 1.47 sharesShortPreviousMonthDate 1671062400 floatShares 15805174737 beta 1.277894 enterpriseValue 2504245641216 priceHint 2 threeYearAverageReturn None lastSplitDate 1598832000 lastSplitFactor 4:1 legalType None lastDividendDate 1667520000 morningStarOverallRating None earningsQuarterlyGrowth -0.134 priceToSalesTrailing12Months 6.2260885 dateShortInterest 1673568000 pegRatio 3.15 ytdReturn None forwardPE 23.071104 lastCapGain None shortPercentOfFloat 0.0077 sharesShortPriorMonth 121757434 impliedSharesOutstanding 0 category None fiveYearAverageReturn None trailingAnnualDividendYield 0.005889968 payoutRatio 0.1545 volume24Hr None navPrice None trailingAnnualDividendRate 0.91 toCurrency None expireDate None algorithm None dividendRate 0.92 exDividendDate 1675987200 circulatingSupply None startDate None trailingPE 25.891342 lastMarket None maxSupply None openInterest None volumeAllCurrencies None strikePrice None ask 152.17 askSize 2200 fromCurrency None fiveYearAvgDividendYield 0.96 bid 152.2 tradeable False dividendYield 0.006 bidSize 3000 coinMarketCapLink None preMarketPrice 152.5 logo_url https://logo.clearbit.com/apple.com trailingPegRatio None
We see Buy and Neutral, which is like Hold. There is also Outperform, which means that it should do better than its peers, and Overweight, which means that you should hold more Apple as a percentage in your portfolio than Apple's percentage weight in the relevant index.
This brings up an interesting point. If you are a portfolio manager, how are you evaluated? The obvious answer is "How much money did I make for my clients?" However, that is incorrect. Finance professionals know that they will have good years and bad years. They are happy to be rewarded for the good years, but they don't want to be punished for the bad ones. Years ago, a smart portfolio manager proposed that he be measured relative to an index or benchmark, such as the S&P 500. Thus, if his fund made 15% last year and the S&P made 10%, then the manager outperformed by 5% or 500 basis points. (A basis point is 1/100th of a percentage point.)
If the fund lost10% last year but the S&P lost 15%, the manager still outperformed by 5% or 500 basis points. So the rating "Overweight" is relative to the appropriate benchmark index.
That's how they keep score in asset management world.
ticker.recommendations
Firm | To Grade | From Grade | Action | |
---|---|---|---|---|
Date | ||||
2012-02-09 08:17:00 | Canaccord Genuity | Buy | main | |
2012-03-08 07:33:00 | FBN Securities | Outperform | main | |
2012-03-13 06:08:00 | Jefferies | Buy | main | |
2012-03-14 06:13:00 | Morgan Stanley | Overweight | main | |
2012-03-14 08:21:00 | Canaccord Genuity | Buy | main | |
... | ... | ... | ... | ... |
2023-02-03 12:42:30 | Cowen & Co. | Outperform | main | |
2023-02-03 13:28:56 | Wedbush | Outperform | main | |
2023-02-03 13:30:22 | Rosenblatt | Buy | main | |
2023-02-03 14:31:06 | DA Davidson | Buy | main | |
2023-02-06 10:31:59 | Evercore ISI Group | Outperform | reit |
889 rows × 4 columns
You could evaluate a stock by looking at the analyst recommendations. For example, instead of merely looking for a BUY or SELL recommendation, you could look for a change in recommendation. A move from a SELL to a BUY or HOLD would be a BUY signal. A move from a BUY to a HOLD or SELL would be a SELL signal.
The author had a friend and colleague decades ago who wanted to start a business based on precisely this premise. He had an MBA from Columbia. He would have done the marketing and sales. I would have implemented the strategy.
I dismissed the idea as being too simple. I was wrong. My colleague is now the President of a major Private Wealth Management firm.
There are lots of data here.
ticker.sustainability
Value | |
---|---|
2022-8 | |
palmOil | False |
controversialWeapons | False |
gambling | False |
socialScore | 6.86 |
nuclear | False |
furLeather | False |
alcoholic | False |
gmo | False |
catholic | False |
socialPercentile | None |
peerCount | 55 |
governanceScore | 9.18 |
environmentPercentile | None |
animalTesting | False |
tobacco | False |
totalEsg | 16.68 |
highestControversy | 3 |
esgPerformance | UNDER_PERF |
coal | False |
pesticides | False |
adult | False |
percentile | 14.68 |
peerGroup | Technology Hardware |
smallArms | False |
environmentScore | 0.65 |
governancePercentile | None |
militaryContract | False |
We can see the recent history of dividend payments.
ticker.actions
Dividends | Stock Splits | |
---|---|---|
Date | ||
2018-02-09 00:00:00-05:00 | 0.1575 | 0.0 |
2018-05-11 00:00:00-04:00 | 0.1825 | 0.0 |
2018-08-10 00:00:00-04:00 | 0.1825 | 0.0 |
2018-11-08 00:00:00-05:00 | 0.1825 | 0.0 |
2019-02-08 00:00:00-05:00 | 0.1825 | 0.0 |
2019-05-10 00:00:00-04:00 | 0.1925 | 0.0 |
2019-08-09 00:00:00-04:00 | 0.1925 | 0.0 |
2019-11-07 00:00:00-05:00 | 0.1925 | 0.0 |
2020-02-07 00:00:00-05:00 | 0.1925 | 0.0 |
2020-05-08 00:00:00-04:00 | 0.2050 | 0.0 |
2020-08-07 00:00:00-04:00 | 0.2050 | 0.0 |
2020-08-31 00:00:00-04:00 | 0.0000 | 4.0 |
2020-11-06 00:00:00-05:00 | 0.2050 | 0.0 |
2021-02-05 00:00:00-05:00 | 0.2050 | 0.0 |
2021-05-07 00:00:00-04:00 | 0.2200 | 0.0 |
2021-08-06 00:00:00-04:00 | 0.2200 | 0.0 |
2021-11-05 00:00:00-04:00 | 0.2200 | 0.0 |
2022-02-04 00:00:00-05:00 | 0.2200 | 0.0 |
2022-05-06 00:00:00-04:00 | 0.2300 | 0.0 |
2022-08-05 00:00:00-04:00 | 0.2300 | 0.0 |
2022-11-04 00:00:00-04:00 | 0.2300 | 0.0 |
ticker.dividends
Date 2018-02-09 00:00:00-05:00 0.1575 2018-05-11 00:00:00-04:00 0.1825 2018-08-10 00:00:00-04:00 0.1825 2018-11-08 00:00:00-05:00 0.1825 2019-02-08 00:00:00-05:00 0.1825 2019-05-10 00:00:00-04:00 0.1925 2019-08-09 00:00:00-04:00 0.1925 2019-11-07 00:00:00-05:00 0.1925 2020-02-07 00:00:00-05:00 0.1925 2020-05-08 00:00:00-04:00 0.2050 2020-08-07 00:00:00-04:00 0.2050 2020-11-06 00:00:00-05:00 0.2050 2021-02-05 00:00:00-05:00 0.2050 2021-05-07 00:00:00-04:00 0.2200 2021-08-06 00:00:00-04:00 0.2200 2021-11-05 00:00:00-04:00 0.2200 2022-02-04 00:00:00-05:00 0.2200 2022-05-06 00:00:00-04:00 0.2300 2022-08-05 00:00:00-04:00 0.2300 2022-11-04 00:00:00-04:00 0.2300 Name: Dividends, dtype: float64
There is lots of information the ticker.info dictionary.
The dividend yield is the dividend per share divided by the price per share.
ticker.info
{'zip': '95014', 'sector': 'Technology', 'fullTimeEmployees': 164000, 'longBusinessSummary': 'Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. It also sells various related services. In addition, 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, and HomePod. Further, it provides AppleCare support and 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. Additionally, the company offers various services, such as Apple Arcade, a game subscription service; Apple Fitness+, a personalized fitness 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 distributes 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 incorporated in 1977 and is headquartered in Cupertino, California.', 'city': 'Cupertino', 'phone': '408 996 1010', 'state': 'CA', 'country': 'United States', 'companyOfficers': [], 'website': 'https://www.apple.com', 'maxAge': 1, 'address1': 'One Apple Park Way', 'industry': 'Consumer Electronics', 'ebitdaMargins': 0.32329, 'profitMargins': 0.24558, 'grossMargins': 0.43058997, 'operatingCashflow': 109189996544, 'revenueGrowth': -0.055, 'operatingMargins': 0.29408002, 'ebitda': 125287997440, 'targetLowPrice': 118, 'recommendationKey': 'buy', 'grossProfits': 170782000000, 'freeCashflow': 84729126912, 'targetMedianPrice': 171.5, 'earningsGrowth': -0.105, 'currentRatio': 0.938, 'returnOnAssets': 0.19569999, 'numberOfAnalystOpinions': 38, 'targetMeanPrice': 168.9, 'debtToEquity': 195.868, 'returnOnEquity': 1.47943, 'targetHighPrice': 210, 'totalCash': 51355000832, 'totalDebt': 111109996544, 'totalRevenue': 387537010688, 'totalCashPerShare': 3.246, 'financialCurrency': 'USD', 'revenuePerShare': 24.084, 'quickRatio': 0.769, 'recommendationMean': 2, 'shortName': 'Apple Inc.', 'longName': 'Apple Inc.', 'isEsgPopulated': False, 'gmtOffSetMilliseconds': '-18000000', 'quoteType': 'EQUITY', 'messageBoardId': 'finmb_24937', 'market': 'us_market', 'annualHoldingsTurnover': None, 'enterpriseToRevenue': 6.462, 'beta3Year': None, 'enterpriseToEbitda': 19.988, '52WeekChange': -0.099965036, 'morningStarRiskRating': None, 'forwardEps': 6.61, 'revenueQuarterlyGrowth': None, 'sharesOutstanding': 15821899776, 'fundInceptionDate': None, 'annualReportExpenseRatio': None, 'totalAssets': None, 'bookValue': 3.581, 'sharesShort': 121868919, 'sharesPercentSharesOut': 0.0077, 'fundFamily': None, 'lastFiscalYearEnd': 1663977600, 'heldPercentInstitutions': 0.61239, 'netIncomeToCommon': 95171002368, 'trailingEps': 5.89, 'lastDividendValue': 0.23, 'SandP52WeekChange': -0.07747549, 'priceToBook': 42.58587, 'heldPercentInsiders': 0.00072999997, 'nextFiscalYearEnd': 1695513600, 'yield': None, 'mostRecentQuarter': 1672444800, 'shortRatio': 1.47, 'sharesShortPreviousMonthDate': 1671062400, 'floatShares': 15805174737, 'beta': 1.277894, 'enterpriseValue': 2504245641216, 'priceHint': 2, 'threeYearAverageReturn': None, 'lastSplitDate': 1598832000, 'lastSplitFactor': '4:1', 'legalType': None, 'lastDividendDate': 1667520000, 'morningStarOverallRating': None, 'earningsQuarterlyGrowth': -0.134, 'priceToSalesTrailing12Months': 6.2260885, 'dateShortInterest': 1673568000, 'pegRatio': 3.15, 'ytdReturn': None, 'forwardPE': 23.071104, 'lastCapGain': None, 'shortPercentOfFloat': 0.0077, 'sharesShortPriorMonth': 121757434, 'impliedSharesOutstanding': 0, 'category': None, 'fiveYearAverageReturn': None, 'trailingAnnualDividendYield': 0.005889968, 'payoutRatio': 0.1545, 'volume24Hr': None, 'navPrice': None, 'trailingAnnualDividendRate': 0.91, 'toCurrency': None, 'expireDate': None, 'algorithm': None, 'dividendRate': 0.92, 'exDividendDate': 1675987200, 'circulatingSupply': None, 'startDate': None, 'trailingPE': 25.891342, 'lastMarket': None, 'maxSupply': None, 'openInterest': None, 'volumeAllCurrencies': None, 'strikePrice': None, 'ask': 152.17, 'askSize': 2200, 'fromCurrency': None, 'fiveYearAvgDividendYield': 0.96, 'bid': 152.2, 'tradeable': False, 'dividendYield': 0.006, 'bidSize': 3000, 'coinMarketCapLink': None, 'preMarketPrice': 152.5, 'logo_url': 'https://logo.clearbit.com/apple.com', 'trailingPegRatio': None}
ticker.info['dividendYield']
0.006
beta is a measure of the stock's volatility relative to the market. Apple is slightly more volatile.
ticker.info['beta']
1.277894
yfinance has a couple target price data points
list(map(lambda x: ticker.info[x],
['targetLowPrice', 'targetMeanPrice','targetMedianPrice','targetHighPrice']))
[118, 168.9, 171.5, 210]
We can get the sector.
ticker.info['industry']
'Consumer Electronics'
We can find out who owns Apple.
ticker.major_holders
0 | 1 | |
---|---|---|
0 | 0.07% | % of Shares Held by All Insider |
1 | 61.24% | % of Shares Held by Institutions |
2 | 61.28% | % of Float Held by Institutions |
3 | 5546 | Number of Institutions Holding Shares |
ticker.institutional_holders
Holder | Shares | Date Reported | % Out | Value | |
---|---|---|---|---|---|
0 | Vanguard Group, Inc. (The) | 1272378901 | 2022-09-29 | 0.0803 | 193859650132 |
1 | Blackrock Inc. | 1020245185 | 2022-09-29 | 0.0644 | 155444557009 |
2 | Berkshire Hathaway, Inc | 894802319 | 2022-09-29 | 0.0565 | 136332081868 |
3 | State Street Corporation | 591543874 | 2022-09-29 | 0.0374 | 90127625003 |
4 | FMR, LLC | 350900116 | 2022-09-29 | 0.0222 | 53463141887 |
5 | Geode Capital Management, LLC | 279758518 | 2022-09-29 | 0.0177 | 42624007973 |
6 | Price (T.Rowe) Associates Inc | 224863541 | 2022-09-29 | 0.0142 | 34260209244 |
7 | Morgan Stanley | 182728771 | 2022-09-29 | 0.0115 | 27840555661 |
8 | Northern Trust Corporation | 176084862 | 2022-09-29 | 0.0111 | 26828289681 |
9 | Bank of America Corporation | 142260591 | 2022-09-29 | 0.0090 | 21674823731 |
ticker.calendar
0 | 1 | |
---|---|---|
Earnings Date | 2023-04-26 10:59:00 | 2023-05-01 12:00:00 |
Earnings Average | 1.43 | 1.43 |
Earnings Low | 1.37 | 1.37 |
Earnings High | 1.56 | 1.56 |
Revenue Average | 93192800000 | 93192800000 |
Revenue Low | 91805900000 | 91805900000 |
Revenue High | 98836000000 | 98836000000 |
yahoo_financials = YahooFinancials('AAPL')
data = yahoo_financials.get_historical_price_data(start_date='2019-01-01',
end_date='2019-12-31',
time_interval='weekly')
aapl_df = pd.DataFrame(data['AAPL']['prices'])
aapl_df = aapl_df.drop('date', axis=1).set_index('formatted_date')
aapl_df.head()
high | low | open | close | volume | adjclose | |
---|---|---|---|---|---|---|
formatted_date | ||||||
2019-01-01 | 39.712502 | 35.500000 | 38.722500 | 36.982498 | 966947200 | 35.694614 |
2019-01-08 | 38.632500 | 37.130001 | 37.389999 | 37.500000 | 725470000 | 36.194099 |
2019-01-15 | 39.470001 | 37.512501 | 37.567501 | 39.205002 | 491411200 | 37.839710 |
2019-01-22 | 39.532501 | 37.924999 | 39.102501 | 39.075001 | 554774800 | 37.714241 |
2019-01-29 | 42.915001 | 38.527500 | 39.062500 | 42.812500 | 830400800 | 41.321583 |
dir(yahoo_financials)
['YAHOO_FINANCIAL_TYPES', '_BASE_YAHOO_URL', '_INTERVAL_DICT', '_MIN_INTERVAL', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_build_api_url', '_build_historical_url', '_cache', '_clean_api_data', '_clean_earnings_data', '_clean_historical_data', '_clean_reports', '_convert_to_utc', '_create_dict_ent', '_determine_numeric_value', '_encode_ticker', '_financial_statement_data', '_format_time', '_get_api_data', '_get_cleaned_sub_dict_ent', '_get_stmt_id', '_get_sub_dict_ent', '_handle_api_dividend_request', '_recursive_api_request', '_reformat_stmt_data_process', '_run_financial_stmt', '_scrape_data', '_stock_price_data', '_stock_summary_data', 'format_date', 'get_200day_moving_avg', 'get_50day_moving_avg', 'get_annual_avg_div_rate', 'get_annual_avg_div_yield', 'get_beta', 'get_book_value', 'get_clean_data', 'get_cost_of_revenue', 'get_currency', 'get_current_change', 'get_current_percent_change', 'get_current_price', 'get_current_volume', 'get_daily_dividend_data', 'get_daily_high', 'get_daily_low', 'get_dividend_rate', 'get_dividend_yield', 'get_earnings_per_share', 'get_ebit', 'get_exdividend_date', 'get_financial_stmts', 'get_five_yr_avg_div_yield', 'get_gross_profit', 'get_historical_price_data', 'get_income_before_tax', 'get_income_tax_expense', 'get_interest_expense', 'get_key_statistics_data', 'get_market_cap', 'get_net_income', 'get_net_income_from_continuing_ops', 'get_num_shares_outstanding', 'get_open_price', 'get_operating_income', 'get_payout_ratio', 'get_pe_ratio', 'get_prev_close_price', 'get_price_to_sales', 'get_reformatted_stmt_data', 'get_report_type', 'get_research_and_development', 'get_stock_data', 'get_stock_dividend_data', 'get_stock_earnings_data', 'get_stock_exchange', 'get_stock_price_data', 'get_stock_quote_type_data', 'get_stock_summary_url', 'get_stock_tech_data', 'get_summary_data', 'get_ten_day_avg_daily_volume', 'get_three_month_avg_daily_volume', 'get_time_code', 'get_total_operating_expense', 'get_total_revenue', 'get_yearly_high', 'get_yearly_low', 'ticker']
for p in dir(yahoo_financials):
if hasattr(getattr(yahoo_financials,p), '__call__'):
if p.startswith('get'):
x = getattr(yahoo_financials, p)()
print (p, '\t', x)
get_200day_moving_avg 147.80174 get_50day_moving_avg 138.8904 get_annual_avg_div_rate 0.91 get_annual_avg_div_yield 0.005889968 get_beta 1.277894 get_book_value 56727000000
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In [26], line 4 2 if hasattr(getattr(yahoo_financials,p), '__call__'): 3 if p.startswith('get'): ----> 4 x = getattr(yahoo_financials, p)() 5 print (p, '\t', x) TypeError: YahooFinanceETL.get_clean_data() missing 2 required positional arguments: 'raw_report_data' and 'report_type'
dir(yahoo_financials.get_clean_data.__func__)
hasattr(yahoo_financials.get_beta, '__call__')
for p in dir(yahoo_financials):
print (p, '\t', getattr(yahoo_financials, p), '\n')
YAHOO_FINANCIAL_TYPES {'income': ['financials', 'incomeStatementHistory', 'incomeStatementHistoryQuarterly'], 'balance': ['balance-sheet', 'balanceSheetHistory', 'balanceSheetHistoryQuarterly', 'balanceSheetStatements'], 'cash': ['cash-flow', 'cashflowStatementHistory', 'cashflowStatementHistoryQuarterly', 'cashflowStatements'], 'keystats': ['key-statistics'], 'history': ['history'], 'profile': ['profile']} _BASE_YAHOO_URL https://finance.yahoo.com/quote/ _INTERVAL_DICT {'daily': '1d', 'weekly': '1wk', 'monthly': '1mo'} _MIN_INTERVAL 7 __class__ <class 'yahoofinancials.yf.YahooFinancials'> __delattr__ <method-wrapper '__delattr__' of YahooFinancials object at 0x7ff1c8898450> _clean_api_data <bound method YahooFinanceETL._clean_api_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _clean_data_process <bound method YahooFinanceETL._clean_data_process of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _clean_earnings_data <bound method YahooFinanceETL._clean_earnings_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _clean_historical_data <bound method YahooFinanceETL._clean_historical_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _clean_reports <bound method YahooFinanceETL._clean_reports of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _convert_to_utc <function YahooFinanceETL._convert_to_utc at 0x7ff1de8d8e00> _create_dict_ent <bound method YahooFinanceETL._create_dict_ent of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _determine_numeric_value <function YahooFinanceETL._determine_numeric_value at 0x7ff1de8d9120> _encode_ticker <function YahooFinanceETL._encode_ticker at 0x7ff1de8d9440> _financial_statement_data <bound method YahooFinancials._financial_statement_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _format_time <bound method YahooFinanceETL._format_time of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _get_api_data <bound method YahooFinanceETL._get_api_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _get_cleaned_sub_dict_ent <bound method YahooFinanceETL._get_cleaned_sub_dict_ent of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _get_proxy <bound method YahooFinanceETL._get_proxy of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _get_stmt_id <bound method YahooFinanceETL._get_stmt_id of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _get_sub_dict_ent <bound method YahooFinanceETL._get_sub_dict_ent of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _get_worker_count <bound method YahooFinanceETL._get_worker_count of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _handle_api_dividend_request <bound method YahooFinanceETL._handle_api_dividend_request of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _recursive_api_request <bound method YahooFinanceETL._recursive_api_request of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _reformat_stmt_data_process <bound method YahooFinanceETL._reformat_stmt_data_process of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _request_handler <bound method YahooFinanceETL._request_handler of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _run_financial_stmt <bound method YahooFinancials._run_financial_stmt of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _scrape_data <bound method YahooFinanceETL._scrape_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _stock_price_data <bound method YahooFinancials._stock_price_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> _stock_summary_data <bound method YahooFinancials._stock_summary_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> concurrent False country US format_date <function YahooFinanceETL.format_date at 0x7ff1de8d8d60> get_200day_moving_avg <bound method YahooFinancials.get_200day_moving_avg of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_50day_moving_avg <bound method YahooFinancials.get_50day_moving_avg of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_annual_avg_div_rate <bound method YahooFinancials.get_annual_avg_div_rate of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_annual_avg_div_yield <bound method YahooFinancials.get_annual_avg_div_yield of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_beta <bound method YahooFinancials.get_beta of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_book_value <bound method YahooFinancials.get_book_value of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_clean_data <bound method YahooFinanceETL.get_clean_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_cost_of_revenue <bound method YahooFinancials.get_cost_of_revenue of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_currency <bound method YahooFinancials.get_currency of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_current_change <bound method YahooFinancials.get_current_change of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_current_percent_change <bound method YahooFinancials.get_current_percent_change of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_current_price <bound method YahooFinancials.get_current_price of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_current_volume <bound method YahooFinancials.get_current_volume of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_daily_dividend_data <bound method YahooFinancials.get_daily_dividend_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_daily_high <bound method YahooFinancials.get_daily_high of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_daily_low <bound method YahooFinancials.get_daily_low of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_dividend_rate <bound method YahooFinancials.get_dividend_rate of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_dividend_yield <bound method YahooFinancials.get_dividend_yield of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_earnings_per_share <bound method YahooFinancials.get_earnings_per_share of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_ebit <bound method YahooFinancials.get_ebit of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_exdividend_date <bound method YahooFinancials.get_exdividend_date of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_financial_data <bound method YahooFinancials.get_financial_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_financial_stmts <bound method YahooFinancials.get_financial_stmts of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_five_yr_avg_div_yield <bound method YahooFinancials.get_five_yr_avg_div_yield of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_gross_profit <bound method YahooFinancials.get_gross_profit of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_historical_price_data <bound method YahooFinancials.get_historical_price_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_income_before_tax <bound method YahooFinancials.get_income_before_tax of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_income_tax_expense <bound method YahooFinancials.get_income_tax_expense of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_interest_expense <bound method YahooFinancials.get_interest_expense of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_key_statistics_data <bound method YahooFinancials.get_key_statistics_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_market_cap <bound method YahooFinancials.get_market_cap of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_net_income <bound method YahooFinancials.get_net_income of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_net_income_from_continuing_ops <bound method YahooFinancials.get_net_income_from_continuing_ops of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_num_shares_outstanding <bound method YahooFinancials.get_num_shares_outstanding of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_open_price <bound method YahooFinancials.get_open_price of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_operating_income <bound method YahooFinancials.get_operating_income of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_payout_ratio <bound method YahooFinancials.get_payout_ratio of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_pe_ratio <bound method YahooFinancials.get_pe_ratio of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_prev_close_price <bound method YahooFinancials.get_prev_close_price of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_price_to_sales <bound method YahooFinancials.get_price_to_sales of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_reformatted_stmt_data <bound method YahooFinanceETL.get_reformatted_stmt_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_report_type <function YahooFinanceETL.get_report_type at 0x7ff1de8d8cc0> get_research_and_development <bound method YahooFinancials.get_research_and_development of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_stock_data <bound method YahooFinanceETL.get_stock_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_stock_dividend_data <bound method YahooFinanceETL.get_stock_dividend_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_stock_earnings_data <bound method YahooFinancials.get_stock_earnings_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_stock_exchange <bound method YahooFinancials.get_stock_exchange of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_stock_price_data <bound method YahooFinancials.get_stock_price_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_stock_profile_data <bound method YahooFinancials.get_stock_profile_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_stock_quote_type_data <bound method YahooFinancials.get_stock_quote_type_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_stock_summary_url <bound method YahooFinancials.get_stock_summary_url of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_stock_tech_data <bound method YahooFinanceETL.get_stock_tech_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_summary_data <bound method YahooFinancials.get_summary_data of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_ten_day_avg_daily_volume <bound method YahooFinancials.get_ten_day_avg_daily_volume of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_three_month_avg_daily_volume <bound method YahooFinancials.get_three_month_avg_daily_volume of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_time_code <bound method YahooFinanceETL.get_time_code of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_total_operating_expense <bound method YahooFinancials.get_total_operating_expense of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_total_revenue <bound method YahooFinancials.get_total_revenue of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_yearly_high <bound method YahooFinancials.get_yearly_high of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> get_yearly_low <bound method YahooFinancials.get_yearly_low of <yahoofinancials.yf.YahooFinancials object at 0x7ff1c8898450>> max_workers 8 proxies None ticker AAPL timeout 30
p = yahoo_financials.get_beta
p()
1.187468
yahoo_financials = YahooFinancials('BTC-USD')
data=yahoo_financials.get_historical_price_data("2019-07-10", "2022-01-31", "monthly")
btc_df = pd.DataFrame(data['BTC-USD']['prices'])
btc_df = btc_df.drop('date', axis=1).set_index('formatted_date')
btc_df.head()
high | low | open | close | volume | adjclose | |
---|---|---|---|---|---|---|
formatted_date | ||||||
2019-08-01 | 12273.821289 | 9421.629883 | 10077.442383 | 9630.664062 | 533984971734 | 9630.664062 |
2019-09-01 | 10898.761719 | 7830.758789 | 9630.592773 | 8293.868164 | 480544963230 | 8293.868164 |
2019-10-01 | 10021.744141 | 7446.988770 | 8299.720703 | 9199.584961 | 595205134748 | 9199.584961 |
2019-11-01 | 9505.051758 | 6617.166992 | 9193.992188 | 7569.629883 | 676919523650 | 7569.629883 |
2019-12-01 | 7743.431641 | 6540.049316 | 7571.616211 | 7193.599121 | 633790373416 | 7193.599121 |
btc_df.tail()
high | low | open | close | volume | adjclose | |
---|---|---|---|---|---|---|
formatted_date | ||||||
2021-09-01 | 52853.765625 | 39787.609375 | 47099.773438 | 43790.894531 | 1102139678824 | 43790.894531 |
2021-10-01 | 66930.390625 | 43320.023438 | 43816.742188 | 61318.957031 | 1153077903534 | 61318.957031 |
2021-11-01 | 68789.625000 | 53569.765625 | 61320.449219 | 57005.425781 | 1053270271383 | 57005.425781 |
2021-12-01 | 59041.683594 | 42874.617188 | 56907.964844 | 46306.445312 | 957047184722 | 46306.445312 |
2022-01-01 | 47881.406250 | 33184.058594 | 46311.746094 | 38483.125000 | 923979037681 | 38483.125000 |
When we speak of "The Market" or a beta relative to the market, we are usually referring to the S and P 500. It has its own ticker: '^GSPC'
ticker = yf.Ticker('^GSPC')
sandp_df = ticker.history(period="10y")
sandp_df['Close'].plot(title="S and P 500 price")
<AxesSubplot: title={'center': 'S and P 500 price'}, xlabel='Date'>
for k,v in ticker.info.items():
print (k, '\t', v, '\n')
exchange SNP shortName S&P 500 exchangeTimezoneName America/New_York exchangeTimezoneShortName EST isEsgPopulated False gmtOffSetMilliseconds -18000000 quoteType INDEX symbol ^GSPC messageBoardId finmb_INDEXGSPC market us_market previousClose 4380.26 regularMarketOpen 4384.57 twoHundredDayAverage 4457.881 trailingAnnualDividendYield None payoutRatio None volume24Hr None regularMarketDayHigh 4394.6 navPrice None averageDailyVolume10Day 3689517000 totalAssets None regularMarketPreviousClose 4380.26 fiftyDayAverage 4588.384 trailingAnnualDividendRate None open 4384.57 toCurrency None averageVolume10days 3689517000 expireDate None yield None algorithm None dividendRate None exDividendDate None beta None circulatingSupply None startDate None regularMarketDayLow 4327.22 priceHint 2 currency USD regularMarketVolume 2583639000 lastMarket None maxSupply None openInterest None marketCap None volumeAllCurrencies None strikePrice None averageVolume 3450258064 priceToSalesTrailing12Months None dayLow 4327.22 ask 4406.55 ytdReturn None askSize 0 volume 2583639000 fiftyTwoWeekHigh 4818.62 forwardPE None maxAge 1 fromCurrency None fiveYearAvgDividendYield None fiftyTwoWeekLow 3723.34 bid 4290.14 tradeable False dividendYield None bidSize 0 dayHigh 4394.6 regularMarketPrice 4348.87 logo_url