{ "cells": [ { "cell_type": "markdown", "id": "93db67d4", "metadata": {}, "source": [ "## yahooquery\n", "\n", "
\n",
"\n",
" \n",
"yahooquery is a Python api to the Yahoo! finance site.\n",
" \n",
"This file resides at 183 rows × 5 columns/c/cs458/www/lectures/yquery.ipynb"
]
},
{
"cell_type": "markdown",
"id": "dddccf83",
"metadata": {},
"source": [
"## Everything you need to know about yahooquery and finance\n",
"\n",
"The fundamental law of finance is:\n",
"\n",
"> Buy low, sell high.\n",
"\n",
"But what do you buy? When they think of finance and investing, most people\n",
"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.\n",
"The market cap is simply the price of a share of stock times the number of shares\n",
"outstanding.)\n",
"\n",
"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\n",
"in which you might choose to invest. Others include bonds (aka, fixed income or debt), \n",
"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).\n",
"\n",
"We are going to focus on equity, that is, stocks. The yfinance Python module provides a\n",
"boatload of information about US stocks and other securities.\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "2b4aa50a",
"metadata": {},
"source": [
"## Risk Management\n",
"\n",
"As we learned from Tversky and Kahnemann and behavioral economists, people are risk\n",
"averse. They don't like losing money. In 1952, Harry Markowitz came up with \n",
"Modern Portfolio Theory which, among other things, \n",
"showed how you can construct a collection or portfolio of stocks to reduce or even\n",
"minimize the risk of the overall investment. One of Markowitz's insights was that \n",
"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 \n",
"by investing stocks that are not correlated with each other. Thus, one stock may\n",
"go up with inflation and another might go down. These movements can offset each other\n",
"and reduce the portfolio's volatility or risk.\n",
"\n",
"You can fully diversify your portfolio by holding 30 or so stocks - assuming that they\n",
"are not correlated. One hundred years ago, investors thought they were diversified if they owned 20 different railroad stocks. Go figure.\n",
"\n",
"These days we measure volatility of the entire stock market with the volatility index or VIX. It is also\n",
"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.\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "fc239b01",
"metadata": {},
"source": [
"## Portfolio Management: Growth and Value\n",
"\n",
"\n",
"We assume that everyone wants to avoid losing money. However, there are many different\n",
"ways to make money. Many stocks pay dividends (usually quarterly) which can provide \n",
"income to the investor. Usually companies that pay dividends are older and more stable\n",
"and established, such as banks and utilities. These stocks are often called value stocks.\n",
"\n",
"Many stocks do not pay dividends. Instead they reinvest that money in the company to \n",
"help it grow and expand. These stocks are often called growth stocks.\n",
"\n",
"Usually, growth stocks are more volatile than value stocks, which is to say that they are more risky.\n",
"\n",
"These categories are not always clear cut.\n",
"\n",
"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 \n",
"as the entire market (usually the S and P 500). A stable stock will have a beta below 1. A\n",
"risky stock will have a beta over 1."
]
},
{
"cell_type": "markdown",
"id": "096203ac",
"metadata": {},
"source": [
"## Portfolio Management: Sector\n",
"\n",
"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\n",
"industries.\n",
"\n",
"Different sectors respond differently to market conditions. In recent years, technology has outperformed sectors like materials or real estate. However, there is no \n",
"clear pattern over time.\n"
]
},
{
"cell_type": "markdown",
"id": "d2639468",
"metadata": {},
"source": [
"## Security Analysis\n",
"\n",
"Many Wall Street firms, like Morgan Stanley, Goldman Sachs, and Merrill Lynch, \n",
"employ finance professionals who advise investors which stocks to buy and sell. For \n",
"example, see a recent Merrill Lynch report on Apple (AAPL). An analysis will usually assign a recommendation of buy, sell, or hold, as\n",
"well as a price target or price objective - their prediction of the price within \n",
"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.\n",
"According to Merrill Lynch, Apple is one of the good guys.\n",
"\n",
"One focus of a security analyst is to predict future earnings. This figure becomes\n",
"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. \n",
"However, the PE ratio varies considerably across industries.\n",
"\n",
"Also, there are quantitative models that can value a stock based on future earnings or \n",
"discounted cash\n",
" 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 \n",
" 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.\n",
"\n",
"In the homework, you are to write some code that could replace a security analyst."
]
},
{
"cell_type": "markdown",
"id": "177c3287",
"metadata": {},
"source": [
"## Model Portfolios\n",
"\n",
"In addition to analyzing companies, Merrill Lynch also provides sample model portfolios, namely:\n",
"\n",
"- Large Cap Defensive\n",
"- Income\n",
"- Income and Growth\n",
"- Growth\n",
"- Mid-Cap\n",
"- International\n",
"\n",
"Each of these portfolios comprise 30 or so individual stocks across a dozen\n",
"industrial sectors. The portfolio specifies the weightings of each holding.\n",
"Every few weeks or months, Merrill Lynch will publish changes to weightings or\n",
"holdings to recalibrate the portfolio. See the \n",
"Research Portfolio Holdings and Primer.\n",
"\n",
"Merrill Lynch publishes a primer which explains the investment philosophy and \n",
"process used to construct these portfolios. The basic premise is that \n",
"each portfolio has its own risk profile, with Large Cap Defensive being safer\n",
"than Income, and so forth.\n",
"\n",
"As a machine learning exercise, you could use the holdings of these portfolios \n",
"as training data to learn the properties of an income stock versus a growth stock."
]
},
{
"cell_type": "markdown",
"id": "d1f42ae2",
"metadata": {},
"source": [
"## Let's go to Python already\n",
"\n",
"\n",
"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\n",
"\n",
"> pip install\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "434fdce3",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import yahooquery as yq"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "d648a760",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'2.4.1'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"yq.__version__"
]
},
{
"cell_type": "markdown",
"id": "112f63be",
"metadata": {},
"source": [
"The documentation for yahooquery is at https://yahooquery.dpguthrie.com/"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "f06d5333",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'2.4.1'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import numpy\n",
"numpy.version.version"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "b62866a3",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Research',\n",
" 'Screener',\n",
" 'Ticker',\n",
" '__all__',\n",
" '__builtins__',\n",
" '__cached__',\n",
" '__doc__',\n",
" '__file__',\n",
" '__loader__',\n",
" '__name__',\n",
" '__package__',\n",
" '__path__',\n",
" '__spec__',\n",
" '__version__',\n",
" 'base',\n",
" 'constants',\n",
" 'get_currencies',\n",
" 'get_exchanges',\n",
" 'get_market_summary',\n",
" 'get_trending',\n",
" 'headless',\n",
" 'misc',\n",
" 'name',\n",
" 'research',\n",
" 'screener',\n",
" 'search',\n",
" 'session_management',\n",
" 'ticker',\n",
" 'utils']"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dir(yq)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "434f81e1",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Research \t \n",
" \n",
"
\n",
"\n",
" \n",
" \n",
" \n",
" period \n",
" strongBuy \n",
" buy \n",
" hold \n",
" sell \n",
" strongSell \n",
" \n",
" \n",
" \n",
" \n",
" symbol \n",
" row \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" aapl \n",
" 0 \n",
" 0m \n",
" 6 \n",
" 22 \n",
" 16 \n",
" 1 \n",
" 1 \n",
" \n",
" \n",
" 1 \n",
" -1m \n",
" 6 \n",
" 22 \n",
" 15 \n",
" 1 \n",
" 2 \n",
" \n",
" \n",
" 2 \n",
" -2m \n",
" 5 \n",
" 24 \n",
" 15 \n",
" 1 \n",
" 3 \n",
" \n",
" \n",
" \n",
"3 \n",
" -3m \n",
" 5 \n",
" 24 \n",
" 15 \n",
" 1 \n",
" 3 \n",
" \n",
" \n",
"
\n",
"\n",
" \n",
" \n",
" \n",
" id \n",
" significance \n",
" headline \n",
" description \n",
" parentTopics \n",
" \n",
" \n",
" \n",
" \n",
" symbol \n",
" date \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" aapl \n",
" 2016-06-02 \n",
" 3385732 \n",
" 1 \n",
" Goldman cuts Apple estimates, price target \n",
" Apple Inc <AAPL.O>: Goldman Sachs cuts price t... \n",
" Performance \n",
" \n",
" \n",
" 2016-06-03 \n",
" 3386781 \n",
" 1 \n",
" S&P assigns 'AA+' rating to Apple Inc's Austra... \n",
" S&P: Apple Inc's Australian dollar-denominated... \n",
" Financing \n",
" \n",
" \n",
" 2016-06-30 \n",
" 3398854 \n",
" 1 \n",
" Nike appoints Tim Cook as lead independent dir... \n",
" Nike Inc <NKE.N>: Nike, Inc. And Phil Knight c... \n",
" Restructuring/Reorganization/Related \n",
" \n",
" \n",
" 2016-07-26 \n",
" 3411989 \n",
" 1 \n",
" Apple says Apple music will be global home of ... \n",
" Apple Inc <AAPL.O>: Host for new series and a ... \n",
" Performance \n",
" \n",
" \n",
" 2016-07-28 \n",
" 3414569 \n",
" 1 \n",
" Moody's assigns AA1 rating to Apple Inc senior... \n",
" Moody's on Apple Inc senior unsecured note iss... \n",
" Performance \n",
" \n",
" \n",
" ... \n",
" ... \n",
" ... \n",
" ... \n",
" ... \n",
" ... \n",
" \n",
" \n",
" 2024-10-30 \n",
" 4918404 \n",
" 1 \n",
" Amplifon CEO doesn't see meaningful impact fro... \n",
" Oct 30 (Reuters) - Amplifon CEO Enrico Vita te... \n",
" Corporate Guidance \n",
" \n",
" \n",
" 2025-07-31 \n",
" 5007692 \n",
" 1 \n",
" Apple CEO Tim Cook Says Open To M&A To Acceler... \n",
" July 31 (Reuters) - Apple Inc <AAPL.O>::APPLE ... \n",
" Corporate Guidance \n",
" \n",
" \n",
" 2025-10-30 \n",
" 5038307 \n",
" 1 \n",
" Apple CEO Cook Says Supply Constrained Today O... \n",
" Oct 30 (Reuters) - Apple Inc <AAPL.O>::APPLE C... \n",
" Corporate Guidance \n",
" \n",
" \n",
" 2025-10-30 \n",
" 5038292 \n",
" 1 \n",
" Apple Expects 'Double Digit' Year Over Year Sa... \n",
" Oct 30 (Reuters) - Apple Inc <AAPL.O>::APPLE E... \n",
" Corporate Guidance \n",
" \n",
" \n",
" \n",
"2025-11-06 \n",
" 5042321 \n",
" 1 \n",
" MP Materials CEO Expects Company To Return To ... \n",
" Nov 6 (Reuters) - Mp Materials Corp <MP.N>::MP... \n",
" Corporate Guidance \n",
"