[Python] Yahooquery: Retrieving and Managing Past Stock and Financial Data

Access to historical pricing and financial data is essential for investment analysis, risk management, and portfolio optimization. Using Yahooquery in Python makes retrieving and managing this information easier. This article provides examples of how to obtain this data using Yahooquery.

Installation of Yahooquery

Yahooquery can be easily installed using the Python package installer, pip. Follow the steps below to install Yahooquery:

1. Open your command prompt or terminal. 2. Enter the following command:

bash
pip install yahooquery

3. Press Enter, and the package will be installed in your Python environment.

For those using a specific environment or requiring more advanced configurations, please refer to the official Yahooquery documentation.

Once installed, you can import Yahooquery into your Python script using the following code:

python
from yahooquery import Ticker

You're now ready to begin retrieving financial data, such as historical pricing, balance sheets, cash flow statements, income statements, and valuation measures, using the Yahooquery package in Python.

Retrieving Specific Historical Pricing Data Using Yahooquery in Python

When it comes to financial analysis, having access to specific historical pricing data is vital. Yahooquery in Python allows for customized retrieval of this information. Here's how you can use it to fetch data according to various parameters:

Parameters

  • period: Length of time to retrieve data. Options include 1d, 5d, 7d, 60d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max.
  • interval: Time between data points. Options include 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo.
  • start: Specific starting date to pull data from, either as a string (format YYYY-MM-DD) or datetime.datetime.
  • end: Specific ending date, similar to the start parameter.
  • adj_timezone: Adjust datetime to the specific symbol's timezone, either True or False.
  • adj_ohlc: Calculates adjusted open, high, low, and close prices according to split and dividend information, either True or False.

Example Code

Below is an example code that fetches Google's stock data for the year 2022 with a daily interval:

python
from yahooquery import Ticker

# Define the ticker symbol for Google
symbol = 'GOOGL'
google = Ticker(symbol)

# Fetch historical pricing data for Google with specified parameters
historical_prices = google.history(period='1y', interval='1d', start='2022-01-01', end='2022-12-31', adj_timezone=True, adj_ohlc=False)

# This will print the historical prices for Google for the year 2022 with a daily interval
print(historical_prices)
                         open        high         low  ...    volume    adjclose  splits
symbol date                                            ...                              
GOOGL  2022-01-03  145.054993  145.850998  143.712997  ...  28646000  144.991501     0.0
...                       ...         ...         ...         ...       ...         ...
       2022-12-30   86.980003   88.300003   86.570000  ...  23986300   88.230003     0.0

The code fetches historical pricing data for Google with a specified time frame, interval, and other adjustments. By modifying the parameters, you can tailor the retrieval to fit various analysis and reporting needs, making Yahooquery an indispensable tool for financial professionals.

Fetching Financials using Yahooquery

Understanding financials is essential for in-depth company analysis. Yahooquery allows for the retrieval of balance sheet, cash flow, income statement, and valuation measures. Let's explore how to fetch each of these details.

Balance Sheet, Cash Flow, and Income Statement

You can retrieve balance sheet, cash flow, and income statement data with the following parameters:

  • frequency: Display either quarterly or annual data. Options include a for annual and q for quarterly.
  • trailing: Include or exclude trailing twelve-month (TTM) data. Options are True or False.

Here's an example code that fetches these three financial statements for Google:

python
from yahooquery import Ticker

symbol = 'GOOGL'
google = Ticker(symbol)

# Fetch annual balance sheet data excluding trailing twelve-month data
balance_sheet = google.balance_sheet(frequency='a', trailing=False)

# Fetch quarterly cash flow data including trailing twelve-month data
cash_flow = google.cash_flow(frequency='q', trailing=True)

# Fetch annual income statement data excluding trailing twelve-month data
income_statement = google.income_statement(frequency='a', trailing=False)

# This will print the retrieved financial statements for Google
print(balance_sheet)
print(cash_flow)
print(income_statement)
         asOfDate periodType  ... TradeandOtherPayablesNonCurrent  WorkingCapital
symbol                        ...                                                
GOOGL  2019-12-31        12M  ...                    9.885000e+09    1.073570e+11
  ...         ...        ...  ...                             ...             ...
GOOGL  2022-12-31        12M  ...                    9.258000e+09    9.549500e+10

[4 rows x 76 columns]
         asOfDate periodType  ... SaleOfInvestment  StockBasedCompensation
symbol                        ...                                         
GOOGL  2022-06-30         3M  ...     2.570800e+10            4.782000e+09
  ...         ...        ...                   ...                     ...
GOOGL  2023-06-30        TTM  ...     7.970300e+10            2.113400e+10

[8 rows x 58 columns]
         asOfDate periodType  ... TotalUnusualItems  TotalUnusualItemsExcludingGoodwill
symbol                        ...                                                      
GOOGL  2019-12-31        12M  ...     -1.697000e+09                       -1.697000e+09
  ...         ...        ...  ...               ...                                 ...
GOOGL  2022-12-31        12M  ...     -6.173000e+09                       -6.173000e+09

[4 rows x 51 columns]

This code retrieves annual and quarterly data for balance sheet, cash flow, and income statement for Google based on the specified parameters.

Valuation Measures

Valuation measures are key financial metrics used to assess a company's value and financial performance. These measures are instrumental in investment analysis, helping investors and analysts gauge the attractiveness of a company's stock, and compare it with others in the industry.

When using Yahooquery to fetch valuation measures, you will receive data that includes the following columns:

  • symbol: Ticker symbol of the company
  • asOfDate: Reference date for the data
  • periodType: Type of financial period (e.g., quarter, year)
  • AccountsPayable, AccountsReceivable, AccumulatedDepreciation, AllowanceForDoubtfulAccountsReceivable, etc.: Various financial metrics representing the company's assets, liabilities, equity, and other financial aspects.

Here's an example code to retrieve Google's valuation measures:

python
from yahooquery import Ticker

symbol = 'GOOGL'
google = Ticker(symbol)

# Retrieve valuation measures for the most recent four quarters and the most recent date
valuation_measures = google.valuation_measures

# This will print the valuation measures for Google
print(valuation_measures)
         asOfDate periodType  EnterpriseValue  ...    PeRatio  PegRatio   PsRatio
symbol                                         ...                               
GOOGL  2022-06-30         3M     1.322004e+12  ...  19.716450    0.7717  5.433710
              ...        ...              ...             ...       ...       ...
GOOGL  2023-08-11        TTM              NaN  ...        NaN       NaN       NaN

[12 rows x 11 columns]

These valuation measures include critical financial data, such as cash, debt, equity, assets, liabilities, and other related metrics. The comprehensive information can be used for:

  • Investment Analysis: Evaluating a company's financial health and growth potential.
  • Comparative Analysis: Comparing a company's valuation with industry peers.
  • Strategic Planning: Assisting in corporate decision-making and strategy formulation.

By understanding and utilizing these valuation measures, investors, analysts, and corporate executives can make more informed and confident decisions, whether they are investing, analyzing, or planning for the future.

FAQs

  1. Is Yahooquery free to use? Yahooquery is an open-source library and can be freely utilized for retrieving financial data from Yahoo Finance.
  2. Can I fetch real-time data using Yahooquery? Yes, Yahooquery supports fetching real-time data by using appropriate functions and parameters.
  3. Is it possible to extract data for multiple symbols at once? Yes, you can pass a list of ticker symbols to the Ticker class and obtain data for multiple symbols simultaneously.
  4. What are the alternative libraries to Yahooquery for financial data? Alternative libraries include yfinance, pandas_datareader, and alpha_vantage.
  5. Can I extract dividend and split history using Yahooquery? Yes, Yahooquery also provides functions to retrieve dividend and split history for the specified ticker symbols.
© Copyright 2023 CLONE CODING