yahooquery¶
yahooquery is a Python api to the Yahoo! finance site.
This file resides at /c/cs458/www/lectures/yquery.ipynb
Everything you need to know about yahooquery and finance¶
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.
Risk Management¶
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.
Portfolio Management: Growth and Value¶
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.
Portfolio Management: Sector¶
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.
Security Analysis¶
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 BUY rating and a price objective of 325 from the current price of 259 (as of the date of the report). 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.
Model Portfolios¶
In addition to analyzing companies, Merrill Lynch also provides sample model portfolios, namely:
- Large Cap Defensive
- Income
- Income and Growth
- Growth
- Mid-Cap
- International
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 and Primer.
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.
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.
Let's go to Python already¶
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 yahooquery as yq
yq.__version__
'2.4.1'
The documentation for yahooquery is at https://yahooquery.dpguthrie.com/
import numpy
numpy.version.version
'2.4.1'
dir(yq)
['Research', 'Screener', 'Ticker', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', 'base', 'constants', 'get_currencies', 'get_exchanges', 'get_market_summary', 'get_trending', 'headless', 'misc', 'name', 'research', 'screener', 'search', 'session_management', 'ticker', 'utils']
for x in dir(yq):
if x.startswith('_'):
next
else:
print (x, '\t', getattr(yq,x))
Research <class 'yahooquery.research.Research'> Screener <class 'yahooquery.screener.Screener'> Ticker <class 'yahooquery.ticker.Ticker'> base <module 'yahooquery.base' from '/home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/base.py'> constants <module 'yahooquery.constants' from '/home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/constants.py'> get_currencies <function get_currencies at 0x71ce3523dbc0> get_exchanges <function get_exchanges at 0x71ce34345da0> get_market_summary <function get_market_summary at 0x71ce34345e40> get_trending <function get_trending at 0x71ce34345ee0> headless <module 'yahooquery.headless' from '/home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/headless.py'> misc <module 'yahooquery.misc' from '/home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/misc.py'> name yahooquery research <module 'yahooquery.research' from '/home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/research.py'> screener <module 'yahooquery.screener' from '/home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/screener.py'> search <function search at 0x71ce3523db20> session_management <module 'yahooquery.session_management' from '/home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/session_management.py'> ticker <module 'yahooquery.ticker' from '/home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/ticker.py'> utils <module 'yahooquery.utils' from '/home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/utils.py'>
from yahooquery import Ticker
dir(Ticker)
['CHUNK', '__annotations__', '__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__', '_adjust_ohlc', '_async_requests', '_chunk_symbols', '_construct_data', '_construct_params', '_construct_urls', '_financials', '_financials_dataframes', '_format_data', '_fund_holdings', '_get_data', '_get_symbol', '_historical_data_to_dataframe', '_history_1m', '_option_dataframe', '_quote_summary', '_quote_summary_dataframe', '_sync_requests', '_to_dataframe', '_validate_response', 'all_financial_data', 'all_modules', 'asset_profile', 'balance_sheet', 'calendar_events', 'cash_flow', 'company_officers', 'corporate_events', 'corporate_guidance', 'country', 'default_query_params', 'dividend_history', 'earning_history', 'earnings', 'earnings_trend', 'esg_scores', 'financial_data', 'fund_bond_holdings', 'fund_bond_ratings', 'fund_category_holdings', 'fund_equity_holdings', 'fund_holding_info', 'fund_ownership', 'fund_performance', 'fund_profile', 'fund_sector_weightings', 'fund_top_holdings', 'get_financial_data', 'get_modules', 'grading_history', 'history', 'income_statement', 'index_trend', 'industry_trend', 'insider_holders', 'insider_transactions', 'institution_ownership', 'key_stats', 'login', 'major_holders', 'news', 'option_chain', 'p_all_financial_data', 'p_balance_sheet', 'p_cash_flow', 'p_company_360', 'p_corporate_events', 'p_fair_value', 'p_get_financial_data', 'p_ideas', 'p_income_statement', 'p_portal', 'p_reports', 'p_technical_events', 'p_technical_insights', 'p_valuation_measures', 'p_value_analyzer', 'p_value_analyzer_drilldown', 'page_views', 'price', 'quote_type', 'quotes', 'recommendation_trend', 'recommendations', 'sec_filings', 'share_purchase_activity', 'summary_detail', 'summary_profile', 'symbols', 'technical_insights', 'validate_symbols', 'valuation_measures']
for x in dir(Ticker):
if x.startswith('_'):
next
else:
print (x, '\t', getattr(Ticker, x))
CHUNK 1500 all_financial_data <function Ticker.all_financial_data at 0x71ce3437e980> all_modules <property object at 0x71ce34363d80> asset_profile <property object at 0x71ce34363e20> balance_sheet <function Ticker.balance_sheet at 0x71ce3437eca0> calendar_events <property object at 0x71ce34363e70> cash_flow <function Ticker.cash_flow at 0x71ce3437ed40> company_officers <property object at 0x71ce34380ae0> corporate_events <property object at 0x71ce34380900> corporate_guidance <property object at 0x71ce343809f0> country <property object at 0x71ce343636a0> default_query_params <property object at 0x71ce3432f150> dividend_history <function Ticker.dividend_history at 0x71ce3438c4a0> earning_history <property object at 0x71ce34380bd0> earnings <property object at 0x71ce34363ec0> earnings_trend <property object at 0x71ce34363f10> esg_scores <property object at 0x71ce34363f60> financial_data <property object at 0x71ce34363fb0> fund_bond_holdings <property object at 0x71ce34380f40> fund_bond_ratings <property object at 0x71ce343813f0> fund_category_holdings <property object at 0x71ce34380fe0> fund_equity_holdings <property object at 0x71ce34381120> fund_holding_info <property object at 0x71ce34381260> fund_ownership <property object at 0x71ce34380c20> fund_performance <property object at 0x71ce343811c0> fund_profile <property object at 0x71ce34381210> fund_sector_weightings <property object at 0x71ce34381530> fund_top_holdings <property object at 0x71ce34381300> get_financial_data <function Ticker.get_financial_data at 0x71ce3437ea20> get_modules <function Ticker.get_modules at 0x71ce3437db20> grading_history <property object at 0x71ce34380c70> history <function Ticker.history at 0x71ce3438c540> income_statement <function Ticker.income_statement at 0x71ce3437f060> index_trend <property object at 0x71ce34380090> industry_trend <property object at 0x71ce343800e0> insider_holders <property object at 0x71ce34380cc0> insider_transactions <property object at 0x71ce34380d10> institution_ownership <property object at 0x71ce34380d60> key_stats <property object at 0x71ce34380130> login <function _YahooFinance.login at 0x71ce3437c4a0> major_holders <property object at 0x71ce34380180> news <function Ticker.news at 0x71ce3437df80> option_chain <property object at 0x71ce34381d50> p_all_financial_data <function Ticker.p_all_financial_data at 0x71ce3437fb00> p_balance_sheet <function Ticker.p_balance_sheet at 0x71ce3437fc40> p_cash_flow <function Ticker.p_cash_flow at 0x71ce3437fce0> p_company_360 <property object at 0x71ce343818a0> p_corporate_events <property object at 0x71ce34381800> p_fair_value <property object at 0x71ce34381670> p_get_financial_data <function Ticker.p_get_financial_data at 0x71ce3437fba0> p_ideas <function Ticker.p_ideas at 0x71ce3438c180> p_income_statement <function Ticker.p_income_statement at 0x71ce3437fe20> p_portal <property object at 0x71ce34381bc0> p_reports <function Ticker.p_reports at 0x71ce3438c0e0> p_technical_events <property object at 0x71ce34381c10> p_technical_insights <property object at 0x71ce34381a80> p_valuation_measures <function Ticker.p_valuation_measures at 0x71ce3438c2c0> p_value_analyzer <property object at 0x71ce34381cb0> p_value_analyzer_drilldown <property object at 0x71ce34381d00> page_views <property object at 0x71ce343801d0> price <property object at 0x71ce34380220> quote_type <property object at 0x71ce34380270> quotes <property object at 0x71ce34380310> recommendation_trend <property object at 0x71ce34380e00> recommendations <property object at 0x71ce34380360> sec_filings <property object at 0x71ce34380ea0> share_purchase_activity <property object at 0x71ce34380400> summary_detail <property object at 0x71ce34380450> summary_profile <property object at 0x71ce343804a0> symbols <property object at 0x71ce34363600> technical_insights <property object at 0x71ce343805e0> validate_symbols <function _YahooFinance.validate_symbols at 0x71ce3437c5e0> valuation_measures <property object at 0x71ce34380a90>
load appl Ticker¶
aapl = Ticker('aapl')
dir(aapl)
['CHUNK', '__annotations__', '__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__', '_adjust_ohlc', '_async_requests', '_chunk_symbols', '_construct_data', '_construct_params', '_construct_urls', '_country', '_country_params', '_financials', '_financials_dataframes', '_format_data', '_fund_holdings', '_get_data', '_get_symbol', '_historical_data_to_dataframe', '_history_1m', '_option_dataframe', '_quote_summary', '_quote_summary_dataframe', '_setup_url', '_symbols', '_sync_requests', '_to_dataframe', '_validate_response', 'all_financial_data', 'all_modules', 'asset_profile', 'balance_sheet', 'calendar_events', 'cash_flow', 'company_officers', 'corporate_events', 'corporate_guidance', 'country', 'crumb', 'default_query_params', 'dividend_history', 'earning_history', 'earnings', 'earnings_trend', 'esg_scores', 'financial_data', 'formatted', 'fund_bond_holdings', 'fund_bond_ratings', 'fund_category_holdings', 'fund_equity_holdings', 'fund_holding_info', 'fund_ownership', 'fund_performance', 'fund_profile', 'fund_sector_weightings', 'fund_top_holdings', 'get_financial_data', 'get_modules', 'grading_history', 'history', 'income_statement', 'index_trend', 'industry_trend', 'insider_holders', 'insider_transactions', 'institution_ownership', 'invalid_symbols', 'key_stats', 'login', 'major_holders', 'news', 'option_chain', 'p_all_financial_data', 'p_balance_sheet', 'p_cash_flow', 'p_company_360', 'p_corporate_events', 'p_fair_value', 'p_get_financial_data', 'p_ideas', 'p_income_statement', 'p_portal', 'p_reports', 'p_technical_events', 'p_technical_insights', 'p_valuation_measures', 'p_value_analyzer', 'p_value_analyzer_drilldown', 'page_views', 'password', 'price', 'progress', 'quote_type', 'quotes', 'recommendation_trend', 'recommendations', 'sec_filings', 'session', 'share_purchase_activity', 'summary_detail', 'summary_profile', 'symbols', 'technical_insights', 'username', 'validate_symbols', 'valuation_measures']
aapl.summary_detail
{'aapl': {'maxAge': 1,
'priceHint': 2,
'previousClose': 269.48,
'open': 272.31,
'dayLow': 272.285,
'dayHigh': 278.81,
'regularMarketPreviousClose': 269.48,
'regularMarketOpen': 272.31,
'regularMarketDayLow': 272.285,
'regularMarketDayHigh': 278.81,
'dividendRate': 1.04,
'dividendYield': 0.0039,
'exDividendDate': '2026-02-08 19:00:00',
'payoutRatio': 0.1304,
'fiveYearAvgDividendYield': 0.52,
'beta': 1.107,
'trailingPE': 34.92152,
'forwardPE': 29.734087,
'volume': 31333837,
'regularMarketVolume': 31333837,
'averageVolume': 47227998,
'averageVolume10days': 58089390,
'averageDailyVolume10Day': 58089390,
'bid': 275.8,
'ask': 276.06,
'bidSize': 100,
'askSize': 100,
'marketCap': 4054863839232,
'fiftyTwoWeekLow': 169.21,
'fiftyTwoWeekHigh': 288.62,
'allTimeHigh': 288.62,
'allTimeLow': 0.049107,
'priceToSalesTrailing12Months': 9.308323,
'fiftyDayAverage': 268.365,
'twoHundredDayAverage': 237.36736,
'trailingAnnualDividendRate': 1.03,
'trailingAnnualDividendYield': 0.0038221758,
'currency': 'USD',
'fromCurrency': None,
'toCurrency': None,
'lastMarket': None,
'coinMarketCapLink': None,
'algorithm': None,
'tradeable': False}}
aapl.asset_profile
{'aapl': {'address1': 'One Apple Park Way',
'city': 'Cupertino',
'state': 'CA',
'zip': '95014',
'country': 'United States',
'phone': '(408) 996-1010',
'website': 'https://www.apple.com',
'industry': 'Consumer Electronics',
'industryKey': 'consumer-electronics',
'industryDisp': 'Consumer Electronics',
'sector': 'Technology',
'sectorKey': 'technology',
'sectorDisp': 'Technology',
'longBusinessSummary': 'Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. 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 Vision Pro, Apple TV, Apple Watch, Beats products, and HomePod, as well as Apple branded and third-party accessories. It also provides AppleCare support and cloud 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, as well as advertising services include third-party licensing arrangements and its own advertising platforms. In addition, the company offers various subscription-based 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 and live sports; 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 and resellers. The company was formerly known as Apple Computer, Inc. and changed its name to Apple Inc. in January 2007. Apple Inc. was founded in 1976 and is headquartered in Cupertino, California.',
'fullTimeEmployees': 150000,
'companyOfficers': [{'maxAge': 1,
'name': 'Mr. Timothy D. Cook',
'age': 64,
'title': 'CEO & Director',
'yearBorn': 1961,
'fiscalYear': 2025,
'totalPay': 16759518,
'exercisedValue': 0,
'unexercisedValue': 0},
{'maxAge': 1,
'name': 'Mr. Kevan Parekh',
'age': 53,
'title': 'Senior VP & CFO',
'yearBorn': 1972,
'fiscalYear': 2025,
'totalPay': 4034174,
'exercisedValue': 0,
'unexercisedValue': 0},
{'maxAge': 1,
'name': 'Mr. Sabih Khan',
'age': 58,
'title': 'Senior VP & Chief Operating Officer',
'yearBorn': 1967,
'fiscalYear': 2025,
'totalPay': 5021905,
'exercisedValue': 0,
'unexercisedValue': 0},
{'maxAge': 1,
'name': 'Ms. Katherine L. Adams',
'age': 61,
'title': 'Senior VP, General Counsel & Secretary',
'yearBorn': 1964,
'fiscalYear': 2025,
'totalPay': 5022482,
'exercisedValue': 0,
'unexercisedValue': 0},
{'maxAge': 1,
'name': "Ms. Deirdre O'Brien",
'age': 58,
'title': 'Senior Vice President of Retail & People',
'yearBorn': 1967,
'fiscalYear': 2025,
'totalPay': 5037867,
'exercisedValue': 0,
'unexercisedValue': 0},
{'maxAge': 1,
'name': 'Mr. Ben Borders',
'age': 44,
'title': 'Principal Accounting Officer',
'yearBorn': 1981,
'fiscalYear': 2025,
'exercisedValue': 0,
'unexercisedValue': 0},
{'maxAge': 1,
'name': 'Suhasini Chandramouli',
'title': 'Director of Investor Relations',
'fiscalYear': 2025,
'exercisedValue': 0,
'unexercisedValue': 0},
{'maxAge': 1,
'name': 'Ms. Kristin Huguet Quayle',
'title': 'Vice President of Worldwide Communications',
'fiscalYear': 2025,
'exercisedValue': 0,
'unexercisedValue': 0},
{'maxAge': 1,
'name': 'Mr. Greg Joswiak',
'title': 'Senior Vice President of Worldwide Marketing',
'fiscalYear': 2025,
'exercisedValue': 0,
'unexercisedValue': 0},
{'maxAge': 1,
'name': 'Mr. Adrian Perica',
'age': 51,
'title': 'Vice President of Corporate Development',
'yearBorn': 1974,
'fiscalYear': 2025,
'exercisedValue': 0,
'unexercisedValue': 0}],
'auditRisk': 7,
'boardRisk': 1,
'compensationRisk': 3,
'shareHolderRightsRisk': 1,
'overallRisk': 1,
'governanceEpochDate': '2026-01-31 19:00:00',
'compensationAsOfEpochDate': '2025-12-30 19:00:00',
'irWebsite': 'http://investor.apple.com/',
'executiveTeam': [],
'maxAge': 86400}}
aapl.calendar_events
{'aapl': {'maxAge': 1,
'earnings': {'earningsDate': ['2026-04-30 17:00:S'],
'earningsCallDate': [1769724000],
'isEarningsDateEstimate': True,
'earningsAverage': 1.94877,
'earningsLow': 1.85,
'earningsHigh': 2.16,
'revenueAverage': 109074306590,
'revenueLow': 105000000000,
'revenueHigh': 112596000000},
'exDividendDate': '2026-02-08 19:00:00',
'dividendDate': '2025-11-12 19:00:00'}}
aapl.esg_scores
{'aapl': 'No fundamentals data found for symbol: AAPL'}
aapl.key_stats
{'aapl': {'maxAge': 1,
'priceHint': 2,
'enterpriseValue': 3979875713024,
'forwardPE': 29.727995,
'profitMargins': 0.27037,
'floatShares': 14655594816,
'sharesOutstanding': 14681140000,
'sharesShort': 113576032,
'sharesShortPriorMonth': 122035714,
'sharesShortPreviousMonthDate': '2025-12-14 19:00:00',
'dateShortInterest': '2026-01-14 19:00:00',
'sharesPercentSharesOut': 0.0077,
'heldPercentInsiders': 0.01702,
'heldPercentInstitutions': 0.64992994,
'shortRatio': 2.61,
'shortPercentOfFloat': 0.0077,
'beta': 1.107,
'impliedSharesOutstanding': 14697926000,
'category': None,
'bookValue': 5.998,
'priceToBook': 46.00385,
'fundFamily': None,
'legalType': None,
'lastFiscalYearEnd': '2025-09-26 20:00:00',
'nextFiscalYearEnd': '2026-09-26 20:00:00',
'mostRecentQuarter': '2025-12-26 19:00:00',
'earningsQuarterlyGrowth': 0.159,
'netIncomeToCommon': 117776998400,
'trailingEps': 7.9,
'forwardEps': 9.27824,
'lastSplitFactor': '4:1',
'lastSplitDate': '2020-08-30 20:00:00',
'enterpriseToRevenue': 9.136,
'enterpriseToEbitda': 26.029,
'52WeekChange': 0.15920329,
'SandP52WeekChange': 0.1412741,
'lastDividendValue': 0.26,
'lastDividendDate': 1762732800,
'latestShareClass': None,
'leadInvestor': None}}
aapl.price
{'aapl': {'maxAge': 1,
'preMarketChangePercent': 0.0107614435,
'preMarketChange': 2.899994,
'preMarketTime': '2026-02-04 09:29:59',
'preMarketPrice': 272.38,
'preMarketSource': 'FREE_REALTIME',
'regularMarketChangePercent': 0.023938995,
'regularMarketChange': 6.4510803,
'regularMarketTime': '2026-02-04 11:41:52',
'priceHint': 2,
'regularMarketPrice': 275.9311,
'regularMarketDayHigh': 278.81,
'regularMarketDayLow': 272.285,
'regularMarketVolume': 31339918,
'regularMarketPreviousClose': 269.48,
'regularMarketSource': 'FREE_REALTIME',
'regularMarketOpen': 272.31,
'exchange': 'NMS',
'exchangeName': 'NasdaqGS',
'exchangeDataDelayedBy': 0,
'marketState': 'REGULAR',
'quoteType': 'EQUITY',
'symbol': 'AAPL',
'underlyingSymbol': None,
'shortName': 'Apple Inc.',
'longName': 'Apple Inc.',
'currency': 'USD',
'quoteSourceName': 'Nasdaq Real Time Price',
'currencySymbol': '$',
'fromCurrency': None,
'toCurrency': None,
'lastMarket': None,
'marketCap': 4055614619648}}
The recommendation trend shows the change in analyst calls in the past 3 months.
aapl.recommendation_trend
| period | strongBuy | buy | hold | sell | strongSell | ||
|---|---|---|---|---|---|---|---|
| symbol | row | ||||||
| aapl | 0 | 0m | 6 | 22 | 16 | 1 | 1 |
| 1 | -1m | 6 | 22 | 15 | 1 | 2 | |
| 2 | -2m | 5 | 24 | 15 | 1 | 3 | |
| 3 | -3m | 5 | 24 | 15 | 1 | 3 |
aapl.corporate_events
| id | significance | headline | description | parentTopics | ||
|---|---|---|---|---|---|---|
| symbol | date | |||||
| aapl | 2016-06-02 | 3385732 | 1 | Goldman cuts Apple estimates, price target | Apple Inc <AAPL.O>: Goldman Sachs cuts price t... | Performance |
| 2016-06-03 | 3386781 | 1 | S&P assigns 'AA+' rating to Apple Inc's Austra... | S&P: Apple Inc's Australian dollar-denominated... | Financing | |
| 2016-06-30 | 3398854 | 1 | Nike appoints Tim Cook as lead independent dir... | Nike Inc <NKE.N>: Nike, Inc. And Phil Knight c... | Restructuring/Reorganization/Related | |
| 2016-07-26 | 3411989 | 1 | Apple says Apple music will be global home of ... | Apple Inc <AAPL.O>: Host for new series and a ... | Performance | |
| 2016-07-28 | 3414569 | 1 | Moody's assigns AA1 rating to Apple Inc senior... | Moody's on Apple Inc senior unsecured note iss... | Performance | |
| ... | ... | ... | ... | ... | ... | |
| 2024-10-30 | 4918404 | 1 | Amplifon CEO doesn't see meaningful impact fro... | Oct 30 (Reuters) - Amplifon CEO Enrico Vita te... | Corporate Guidance | |
| 2025-07-31 | 5007692 | 1 | Apple CEO Tim Cook Says Open To M&A To Acceler... | July 31 (Reuters) - Apple Inc <AAPL.O>::APPLE ... | Corporate Guidance | |
| 2025-10-30 | 5038307 | 1 | Apple CEO Cook Says Supply Constrained Today O... | Oct 30 (Reuters) - Apple Inc <AAPL.O>::APPLE C... | Corporate Guidance | |
| 2025-10-30 | 5038292 | 1 | Apple Expects 'Double Digit' Year Over Year Sa... | Oct 30 (Reuters) - Apple Inc <AAPL.O>::APPLE E... | Corporate Guidance | |
| 2025-11-06 | 5042321 | 1 | MP Materials CEO Expects Company To Return To ... | Nov 6 (Reuters) - Mp Materials Corp <MP.N>::MP... | Corporate Guidance |
183 rows × 5 columns
load S and P stock prices for year to date as a data frame¶
tables = pd.read_html("https://en.wikipedia.org/wiki/List_of_S%26P_500_companies")
sp500 = tables[0]['Symbol'].tolist()
sp500 = [symbol.replace(".", "-") for symbol in sp500]
--------------------------------------------------------------------------- HTTPError Traceback (most recent call last) Cell In[19], line 1 ----> 1 tables = pd.read_html("https://en.wikipedia.org/wiki/List_of_S%26P_500_companies") 2 sp500 = tables[0]['Symbol'].tolist() 3 sp500 = [symbol.replace(".", "-") for symbol in sp500] File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/pandas/io/html.py:1226, in read_html(io, match, flavor, header, index_col, skiprows, attrs, parse_dates, thousands, encoding, decimal, converters, na_values, keep_default_na, displayed_only, extract_links, dtype_backend, storage_options) 1222 check_dtype_backend(dtype_backend) 1224 io = stringify_path(io) -> 1226 return _parse( 1227 flavor=flavor, 1228 io=io, 1229 match=match, 1230 header=header, 1231 index_col=index_col, 1232 skiprows=skiprows, 1233 parse_dates=parse_dates, 1234 thousands=thousands, 1235 attrs=attrs, 1236 encoding=encoding, 1237 decimal=decimal, 1238 converters=converters, 1239 na_values=na_values, 1240 keep_default_na=keep_default_na, 1241 displayed_only=displayed_only, 1242 extract_links=extract_links, 1243 dtype_backend=dtype_backend, 1244 storage_options=storage_options, 1245 ) File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/pandas/io/html.py:979, in _parse(flavor, io, match, attrs, encoding, displayed_only, extract_links, storage_options, **kwargs) 968 p = parser( 969 io, 970 compiled_match, (...) 975 storage_options, 976 ) 978 try: --> 979 tables = p.parse_tables() 980 except ValueError as caught: 981 # if `io` is an io-like object, check if it's seekable 982 # and try to rewind it before trying the next parser 983 if hasattr(io, "seekable") and io.seekable(): File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/pandas/io/html.py:237, in _HtmlFrameParser.parse_tables(self) 229 def parse_tables(self): 230 """ 231 Parse and return all tables from the DOM. 232 (...) 235 list of parsed (header, body, footer) tuples from tables. 236 """ --> 237 tables = self._parse_tables(self._build_doc(), self.match, self.attrs) 238 return (self._parse_thead_tbody_tfoot(table) for table in tables) File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/pandas/io/html.py:789, in _LxmlFrameParser._build_doc(self) 786 parser = HTMLParser(recover=True, encoding=self.encoding) 788 if is_url(self.io): --> 789 with get_handle(self.io, "r", storage_options=self.storage_options) as f: 790 r = parse(f.handle, parser=parser) 791 else: 792 # try to parse the input in the simplest way File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/pandas/io/common.py:772, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options) 769 codecs.lookup_error(errors) 771 # open URLs --> 772 ioargs = _get_filepath_or_buffer( 773 path_or_buf, 774 encoding=encoding, 775 compression=compression, 776 mode=mode, 777 storage_options=storage_options, 778 ) 780 handle = ioargs.filepath_or_buffer 781 handles: list[BaseBuffer] File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/pandas/io/common.py:404, in _get_filepath_or_buffer(filepath_or_buffer, encoding, compression, mode, storage_options) 402 # assuming storage_options is to be interpreted as headers 403 req_info = urllib.request.Request(filepath_or_buffer, headers=storage_options) --> 404 with urlopen(req_info) as req: 405 content_encoding = req.headers.get("Content-Encoding", None) 406 if content_encoding == "gzip": 407 # Override compression based on Content-Encoding header File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/pandas/io/common.py:281, in urlopen(*args, **kwargs) 275 """ 276 Lazy-import wrapper for stdlib urlopen, as that imports a big chunk of 277 the stdlib. 278 """ 279 import urllib.request --> 281 return urllib.request.urlopen(*args, **kwargs) File /usr/lib/python3.12/urllib/request.py:215, in urlopen(url, data, timeout, cafile, capath, cadefault, context) 213 else: 214 opener = _opener --> 215 return opener.open(url, data, timeout) File /usr/lib/python3.12/urllib/request.py:521, in OpenerDirector.open(self, fullurl, data, timeout) 519 for processor in self.process_response.get(protocol, []): 520 meth = getattr(processor, meth_name) --> 521 response = meth(req, response) 523 return response File /usr/lib/python3.12/urllib/request.py:630, in HTTPErrorProcessor.http_response(self, request, response) 627 # According to RFC 2616, "2xx" code indicates that the client's 628 # request was successfully received, understood, and accepted. 629 if not (200 <= code < 300): --> 630 response = self.parent.error( 631 'http', request, response, code, msg, hdrs) 633 return response File /usr/lib/python3.12/urllib/request.py:559, in OpenerDirector.error(self, proto, *args) 557 if http_err: 558 args = (dict, 'default', 'http_error_default') + orig_args --> 559 return self._call_chain(*args) File /usr/lib/python3.12/urllib/request.py:492, in OpenerDirector._call_chain(self, chain, kind, meth_name, *args) 490 for handler in handlers: 491 func = getattr(handler, meth_name) --> 492 result = func(*args) 493 if result is not None: 494 return result File /usr/lib/python3.12/urllib/request.py:639, in HTTPDefaultErrorHandler.http_error_default(self, req, fp, code, msg, hdrs) 638 def http_error_default(self, req, fp, code, msg, hdrs): --> 639 raise HTTPError(req.full_url, code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden
%%time
tickers = Ticker(aapl, asynchronous=True)
yq_data = tickers.history(period='ytd', interval='1d')
CPU times: user 42.6 ms, sys: 9.37 ms, total: 52 ms Wall time: 1.07 s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[20], line 1 ----> 1 get_ipython().run_cell_magic('time', '', "tickers = Ticker(aapl, asynchronous=True)\nyq_data = tickers.history(period='ytd', interval='1d')\n") File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/IPython/core/interactiveshell.py:2572, in InteractiveShell.run_cell_magic(self, magic_name, line, cell) 2570 with self.builtin_trap: 2571 args = (magic_arg_s, cell) -> 2572 result = fn(*args, **kwargs) 2574 # The code below prevents the output from being displayed 2575 # when using magics with decorator @output_can_be_silenced 2576 # when the last Python token in the expression is a ';'. 2577 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False): File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/IPython/core/magics/execution.py:1447, in ExecutionMagics.time(self, line, cell, local_ns) 1445 if interrupt_occured: 1446 if exit_on_interrupt and captured_exception: -> 1447 raise captured_exception 1448 return 1449 return out File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/IPython/core/magics/execution.py:1411, in ExecutionMagics.time(self, line, cell, local_ns) 1409 st = clock2() 1410 try: -> 1411 exec(code, glob, local_ns) 1412 out = None 1413 # multi-line %%time case File <timed exec>:2 File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/ticker.py:1284, in Ticker.history(self, period, interval, start, end, adj_timezone, adj_ohlc) 1282 df = self._history_1m(adj_timezone, adj_ohlc) 1283 else: -> 1284 data = self._get_data("chart", params) 1285 df = self._historical_data_to_dataframe(data, params, adj_timezone) 1286 if adj_ohlc and "adjclose" in df: File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/base.py:181, in _YahooFinance._get_data(self, key, params, **kwargs) 179 config = CONFIG[key] 180 params = self._construct_params(config, params) --> 181 urls = self._construct_urls(config, params, **kwargs) 182 response_field = config["response_field"] 183 try: File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahooquery/base.py:255, in _YahooFinance._construct_urls(self, config, params, **kwargs) 249 else: 250 ls = ( 251 self._symbols 252 if isinstance(self.session, FuturesSession) 253 else tqdm(self._symbols, disable=not self.progress) 254 ) --> 255 urls = [ 256 self.session.get( 257 url=config["path"].format(**{"symbol": symbol}), params=params 258 ) 259 for symbol in ls 260 ] 261 return urls TypeError: 'Ticker' object is not iterable
aapl_df.tail()
plot Apple stock price for the past 5 years¶
import matplotlib
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) Cell In[21], line 1 ----> 1 import matplotlib ModuleNotFoundError: No module named 'matplotlib'
ticker = Ticker('AAPL')
aapl_df = ticker.history(period="5y")
aapl_df['Close'].plot(title="APPLE's stock price")
/home/accts/sbs5/.local/lib/python3.11/site-packages/yahooquery/utils/__init__.py:1470: FutureWarning: 'S' is deprecated and will be removed in a future version. Please use 's' instead of 'S'.
has_live_indice = index_utc[-1] >= last_trade - pd.Timedelta(2, "S")
/home/accts/sbs5/.local/lib/python3.11/site-packages/yahooquery/ticker.py:1333: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.
The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.
For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.
df["dividends"].fillna(0, inplace=True)
/home/accts/sbs5/.local/lib/python3.11/site-packages/yahooquery/ticker.py:1335: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.
The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.
For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.
df["splits"].fillna(0, inplace=True)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) File ~/.local/lib/python3.11/site-packages/pandas/core/indexes/base.py:3802, in Index.get_loc(self, key) 3801 try: -> 3802 return self._engine.get_loc(casted_key) 3803 except KeyError as err: File index.pyx:153, in pandas._libs.index.IndexEngine.get_loc() File index.pyx:182, in pandas._libs.index.IndexEngine.get_loc() File pandas/_libs/hashtable_class_helper.pxi:7081, in pandas._libs.hashtable.PyObjectHashTable.get_item() File pandas/_libs/hashtable_class_helper.pxi:7089, in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 'Close' The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) Cell In[28], line 3 1 ticker = Ticker('AAPL') 2 aapl_df = ticker.history(period="5y") ----> 3 aapl_df['Close'].plot(title="APPLE's stock price") File ~/.local/lib/python3.11/site-packages/pandas/core/frame.py:4090, in DataFrame.__getitem__(self, key) 4088 if self.columns.nlevels > 1: 4089 return self._getitem_multilevel(key) -> 4090 indexer = self.columns.get_loc(key) 4091 if is_integer(indexer): 4092 indexer = [indexer] File ~/.local/lib/python3.11/site-packages/pandas/core/indexes/base.py:3809, in Index.get_loc(self, key) 3804 if isinstance(casted_key, slice) or ( 3805 isinstance(casted_key, abc.Iterable) 3806 and any(isinstance(x, slice) for x in casted_key) 3807 ): 3808 raise InvalidIndexError(key) -> 3809 raise KeyError(key) from err 3810 except TypeError: 3811 # If we have a listlike key, _check_indexing_error will raise 3812 # InvalidIndexError. Otherwise we fall through and re-raise 3813 # the TypeError. 3814 self._check_indexing_error(key) KeyError: 'Close'
YahooFinancials - Apple¶
from yahoofinancials import YahooFinancials
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()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[22], line 2 1 yahoo_financials = YahooFinancials('AAPL') ----> 2 data = yahoo_financials.get_historical_price_data(start_date='2019-01-01', 3 end_date='2019-12-31', 4 time_interval='weekly') 5 aapl_df = pd.DataFrame(data['AAPL']['prices']) 6 aapl_df = aapl_df.drop('date', axis=1).set_index('formatted_date') File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahoofinancials/yf.py:163, in YahooFinancials.get_historical_price_data(self, start_date, end_date, time_interval) 161 end = self.format_date(end_date) 162 hist_obj = {'start': start, 'end': end, 'interval': interval_code} --> 163 return self.get_stock_data('history', hist_obj=hist_obj) File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahoofinancials/data.py:631, in YahooFinanceData.get_stock_data(self, statement_type, tech_type, report_name, hist_obj) 629 if isinstance(self.ticker, str): 630 dict_ent = self._retry_create_dict_ent(self.ticker, statement_type, tech_type, report_name, hist_obj) --> 631 data.update(dict_ent) 632 else: 633 if self.concurrent: TypeError: 'NoneType' object is not iterable
dir(yahoo_financials)
['YAHOO_FINANCIAL_TYPES', '_BASE_YAHOO_URL', '_INTERVAL_DICT', '_MIN_INTERVAL', '__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__', '_build_api_url', '_cache', '_clean_api_data', '_clean_data_process', '_clean_earnings_data', '_clean_historical_data', '_clean_reports', '_construct_url', '_convert_to_utc', '_create_dict_ent', '_determine_numeric_value', '_encode_ticker', '_financial_statement_data', '_format_raw_fundamental_data', '_format_raw_module_data', '_format_time', '_get_analytic_data', '_get_api_data', '_get_cleaned_sub_dict_ent', '_get_historical_data', '_get_proxy', '_get_stmt_id', '_get_sub_dict_ent', '_get_worker_count', '_handle_api_dividend_request', '_recursive_api_request', '_reformat_stmt_data_process', '_reformat_stmt_data_process_flat', '_request_handler', '_retry_create_dict_ent', '_run_financial_stmt', '_stock_price_data', '_stock_summary_data', 'concurrent', 'country', 'flat_format', '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_esg_score_data', 'get_exdividend_date', 'get_financial_data', '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_insights', '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_recommendations', '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_profile_data', 'get_stock_quote_type_data', 'get_stock_summary_url', 'get_stock_tech_data', 'get_summary_data', 'get_ten_day_avg_daily_volume', 'get_time_code', 'get_total_operating_expense', 'get_total_revenue', 'get_yearly_high', 'get_yearly_low', 'max_workers', 'proxies', 'session', 'ticker', 'timeout']
dir(yahoo_financials.get_clean_data.__func__)
['__annotations__', '__builtins__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__getstate__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__type_params__']
hasattr(yahoo_financials.get_beta, '__call__')
True
for p in dir(yahoo_financials):
print (p, '\t', getattr(yahoo_financials, p), '\n')
YAHOO_FINANCIAL_TYPES {'income': ['income_statement', 'incomeStatementHistory', 'incomeStatementHistoryQuarterly', 'incomeStatements'], 'balance': ['balance_sheet', 'balanceSheetHistory', 'balanceSheetHistoryQuarterly', 'balanceSheetStatements'], 'cash': ['cash_flow', 'cashflowStatementHistory', 'cashflowStatementHistoryQuarterly', 'cashflowStatements'], 'keystats': ['key-statistics'], 'history': ['history'], 'profile': ['summaryProfile']}
_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 0x7c63fd367620>
__dict__ {'ticker': 'AAPL', 'country': 'US', 'concurrent': False, 'max_workers': 8, 'timeout': 30, 'proxies': None, 'session': None, 'flat_format': False, '_cache': {}}
__dir__ <built-in method __dir__ of YahooFinancials object at 0x7c63fd367620>
__doc__
Arguments
----------
tickers: str or list
Ticker or listed collection of tickers
Keyword Arguments
-----------------
concurrent: bool, default False, optional
Defines whether the requests are made synchronously or asynchronously.
country: str, default 'US', optional
This allows you to alter the region, lang, corsDomain parameter sent with each request based on selected country
max_workers: int, default 8, optional
Defines the number of workers used to make concurrent requests.
Only relevant if concurrent=True
timeout: int, default 30, optional
Defines how long a request will stay open.
proxies: str or list, default None, optional
Defines any proxies to use during this instantiation.
flat_format: bool, default False, optional
If set to True, returns fundamental data in a flattened format, i.e. without the list of dicts.
__eq__ <method-wrapper '__eq__' of YahooFinancials object at 0x7c63fd367620>
__format__ <built-in method __format__ of YahooFinancials object at 0x7c63fd367620>
__ge__ <method-wrapper '__ge__' of YahooFinancials object at 0x7c63fd367620>
__getattribute__ <method-wrapper '__getattribute__' of YahooFinancials object at 0x7c63fd367620>
__getstate__ <built-in method __getstate__ of YahooFinancials object at 0x7c63fd367620>
__gt__ <method-wrapper '__gt__' of YahooFinancials object at 0x7c63fd367620>
__hash__ <method-wrapper '__hash__' of YahooFinancials object at 0x7c63fd367620>
__init__ <bound method YahooFinanceData.__init__ of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
__init_subclass__ <built-in method __init_subclass__ of type object at 0x2c50fdc0>
__le__ <method-wrapper '__le__' of YahooFinancials object at 0x7c63fd367620>
__lt__ <method-wrapper '__lt__' of YahooFinancials object at 0x7c63fd367620>
__module__ yahoofinancials.yf
__ne__ <method-wrapper '__ne__' of YahooFinancials object at 0x7c63fd367620>
__new__ <built-in method __new__ of type object at 0xa43820>
__reduce__ <built-in method __reduce__ of YahooFinancials object at 0x7c63fd367620>
__reduce_ex__ <built-in method __reduce_ex__ of YahooFinancials object at 0x7c63fd367620>
__repr__ <method-wrapper '__repr__' of YahooFinancials object at 0x7c63fd367620>
__setattr__ <method-wrapper '__setattr__' of YahooFinancials object at 0x7c63fd367620>
__sizeof__ <built-in method __sizeof__ of YahooFinancials object at 0x7c63fd367620>
__str__ <method-wrapper '__str__' of YahooFinancials object at 0x7c63fd367620>
__subclasshook__ <built-in method __subclasshook__ of type object at 0x2c50fdc0>
__weakref__ None
_build_api_url <bound method YahooFinanceData._build_api_url of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_cache {}
_clean_api_data <bound method YahooFinanceData._clean_api_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_clean_data_process <bound method YahooFinanceData._clean_data_process of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_clean_earnings_data <bound method YahooFinanceData._clean_earnings_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_clean_historical_data <bound method YahooFinanceData._clean_historical_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_clean_reports <bound method YahooFinanceData._clean_reports of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_construct_url <bound method YahooFinanceData._construct_url of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_convert_to_utc <function YahooFinanceData._convert_to_utc at 0x7c63fde5a520>
_create_dict_ent <bound method YahooFinanceData._create_dict_ent of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_determine_numeric_value <function YahooFinanceData._determine_numeric_value at 0x7c63fde5aa20>
_encode_ticker <function YahooFinanceData._encode_ticker at 0x7c63fde5ad40>
_financial_statement_data <bound method YahooFinancials._financial_statement_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_format_raw_fundamental_data <function YahooFinanceData._format_raw_fundamental_data at 0x7c63fde5a840>
_format_raw_module_data <function YahooFinanceData._format_raw_module_data at 0x7c63fde5a8e0>
_format_time <bound method YahooFinanceData._format_time of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_get_analytic_data <bound method YahooFinancials._get_analytic_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_get_api_data <bound method YahooFinanceData._get_api_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_get_cleaned_sub_dict_ent <bound method YahooFinanceData._get_cleaned_sub_dict_ent of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_get_historical_data <bound method YahooFinanceData._get_historical_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_get_proxy <bound method YahooFinanceData._get_proxy of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_get_stmt_id <bound method YahooFinanceData._get_stmt_id of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_get_sub_dict_ent <bound method YahooFinanceData._get_sub_dict_ent of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_get_worker_count <bound method YahooFinanceData._get_worker_count of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_handle_api_dividend_request <bound method YahooFinanceData._handle_api_dividend_request of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_recursive_api_request <bound method YahooFinanceData._recursive_api_request of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_reformat_stmt_data_process <function YahooFinanceData._reformat_stmt_data_process at 0x7c63fde5b2e0>
_reformat_stmt_data_process_flat <function YahooFinanceData._reformat_stmt_data_process_flat at 0x7c63fde5b380>
_request_handler <bound method YahooFinanceData._request_handler of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_retry_create_dict_ent <bound method YahooFinanceData._retry_create_dict_ent of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_run_financial_stmt <bound method YahooFinancials._run_financial_stmt of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_stock_price_data <bound method YahooFinancials._stock_price_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
_stock_summary_data <bound method YahooFinancials._stock_summary_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
concurrent False
country US
flat_format False
format_date <function YahooFinanceData.format_date at 0x7c63fde5a480>
get_200day_moving_avg <bound method YahooFinancials.get_200day_moving_avg of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_50day_moving_avg <bound method YahooFinancials.get_50day_moving_avg of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_annual_avg_div_rate <bound method YahooFinancials.get_annual_avg_div_rate of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_annual_avg_div_yield <bound method YahooFinancials.get_annual_avg_div_yield of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_beta <bound method YahooFinancials.get_beta of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_book_value <bound method YahooFinancials.get_book_value of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_clean_data <bound method YahooFinanceData.get_clean_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_cost_of_revenue <bound method YahooFinancials.get_cost_of_revenue of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_currency <bound method YahooFinancials.get_currency of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_current_change <bound method YahooFinancials.get_current_change of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_current_percent_change <bound method YahooFinancials.get_current_percent_change of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_current_price <bound method YahooFinancials.get_current_price of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_current_volume <bound method YahooFinancials.get_current_volume of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_daily_dividend_data <bound method YahooFinancials.get_daily_dividend_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_daily_high <bound method YahooFinancials.get_daily_high of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_daily_low <bound method YahooFinancials.get_daily_low of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_dividend_rate <bound method YahooFinancials.get_dividend_rate of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_dividend_yield <bound method YahooFinancials.get_dividend_yield of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_earnings_per_share <bound method YahooFinancials.get_earnings_per_share of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_ebit <bound method YahooFinancials.get_ebit of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_esg_score_data <bound method YahooFinancials.get_esg_score_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_exdividend_date <bound method YahooFinancials.get_exdividend_date of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_financial_data <bound method YahooFinancials.get_financial_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_financial_stmts <bound method YahooFinancials.get_financial_stmts of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_five_yr_avg_div_yield <bound method YahooFinancials.get_five_yr_avg_div_yield of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_gross_profit <bound method YahooFinancials.get_gross_profit of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_historical_price_data <bound method YahooFinancials.get_historical_price_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_income_before_tax <bound method YahooFinancials.get_income_before_tax of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_income_tax_expense <bound method YahooFinancials.get_income_tax_expense of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_insights <bound method YahooFinancials.get_insights of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_interest_expense <bound method YahooFinancials.get_interest_expense of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_key_statistics_data <bound method YahooFinancials.get_key_statistics_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_market_cap <bound method YahooFinancials.get_market_cap of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_net_income <bound method YahooFinancials.get_net_income of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_net_income_from_continuing_ops <bound method YahooFinancials.get_net_income_from_continuing_ops of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_num_shares_outstanding <bound method YahooFinancials.get_num_shares_outstanding of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_open_price <bound method YahooFinancials.get_open_price of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_operating_income <bound method YahooFinancials.get_operating_income of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_payout_ratio <bound method YahooFinancials.get_payout_ratio of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_pe_ratio <bound method YahooFinancials.get_pe_ratio of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_prev_close_price <bound method YahooFinancials.get_prev_close_price of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_price_to_sales <bound method YahooFinancials.get_price_to_sales of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_recommendations <bound method YahooFinancials.get_recommendations of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_reformatted_stmt_data <bound method YahooFinanceData.get_reformatted_stmt_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_report_type <function YahooFinanceData.get_report_type at 0x7c63fde5a3e0>
get_research_and_development <bound method YahooFinancials.get_research_and_development of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_stock_data <bound method YahooFinanceData.get_stock_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_stock_dividend_data <bound method YahooFinanceData.get_stock_dividend_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_stock_earnings_data <bound method YahooFinancials.get_stock_earnings_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_stock_exchange <bound method YahooFinancials.get_stock_exchange of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_stock_price_data <bound method YahooFinancials.get_stock_price_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_stock_profile_data <bound method YahooFinancials.get_stock_profile_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_stock_quote_type_data <bound method YahooFinancials.get_stock_quote_type_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_stock_summary_url <bound method YahooFinancials.get_stock_summary_url of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_stock_tech_data <bound method YahooFinanceData.get_stock_tech_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_summary_data <bound method YahooFinancials.get_summary_data of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_ten_day_avg_daily_volume <bound method YahooFinancials.get_ten_day_avg_daily_volume of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_time_code <bound method YahooFinanceData.get_time_code of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_total_operating_expense <bound method YahooFinancials.get_total_operating_expense of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_total_revenue <bound method YahooFinancials.get_total_revenue of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_yearly_high <bound method YahooFinancials.get_yearly_high of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
get_yearly_low <bound method YahooFinancials.get_yearly_low of <yahoofinancials.yf.YahooFinancials object at 0x7c63fd367620>>
max_workers 8
proxies None
session None
ticker AAPL
timeout 30
YahooFinancials - Bitcoin¶
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()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[27], line 2 1 yahoo_financials = YahooFinancials('BTC-USD') ----> 2 data=yahoo_financials.get_historical_price_data("2019-07-10", "2022-01-31", "monthly") 3 btc_df = pd.DataFrame(data['BTC-USD']['prices']) 4 btc_df = btc_df.drop('date', axis=1).set_index('formatted_date') File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahoofinancials/yf.py:163, in YahooFinancials.get_historical_price_data(self, start_date, end_date, time_interval) 161 end = self.format_date(end_date) 162 hist_obj = {'start': start, 'end': end, 'interval': interval_code} --> 163 return self.get_stock_data('history', hist_obj=hist_obj) File /home/httpd/html/zoo/classes/cs458/lectures/venv/lib/python3.12/site-packages/yahoofinancials/data.py:631, in YahooFinanceData.get_stock_data(self, statement_type, tech_type, report_name, hist_obj) 629 if isinstance(self.ticker, str): 630 dict_ent = self._retry_create_dict_ent(self.ticker, statement_type, tech_type, report_name, hist_obj) --> 631 data.update(dict_ent) 632 else: 633 if self.concurrent: TypeError: 'NoneType' object is not iterable
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 |