CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
DanielBarnes18

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: DanielBarnes18/IBM-Data-Science-Professional-Certificate
Path: blob/main/05. Python Project for Data Science/Extracting Stock Data Using the yfinance Library.ipynb
Views: 4585
Kernel: Python 3
cognitiveclass.ai logo

Extracting Stock Data Using a Python Library

A company's stock share is a piece of the company more precisely:

A stock (also known as equity) is a security that represents the ownership of a fraction of a corporation. This entitles the owner of the stock to a proportion of the corporation's assets and profits equal to how much stock they own. Units of stock are called "shares." [1]

An investor can buy a stock and sell it later. If the stock price increases, the investor profits, If it decreases,the investor with incur a loss.  Determining the stock price is complex; it depends on the number of outstanding shares, the size of the company's future profits, and much more. People trade stocks throughout the day the stock ticker is a report of the price of a certain stock, updated continuously throughout the trading session by the various stock market exchanges.

You are a data scientist working for a hedge fund; it's your job to determine any suspicious stock activity. In this lab you will extract stock data using a Python library. We will use the [removed]yfinance library, it allows us to extract data for stocks returning data in a pandas dataframe. You will use the lab to extract.

Table of Contents

  • Using yfinance to Extract Stock Info
  • Using yfinance to Extract Historical Share Price Data
  • Using yfinance to Extract Historical Dividends Data
  • Exercise

#!python -m pip install yfinance #!python -m pip install pandas
import yfinance as yf import pandas as pd

Using the yfinance Library to Extract Stock Data

Using the Ticker module we can create an object that will allow us to access functions to extract data. To do this we need to provide the ticker symbol for the stock, here the company is Apple and the ticker symbol is AAPL.

apple = yf.Ticker("AAPL")

Now we can access functions and variables to extract the type of data we need. You can view them and what they represent here https://aroussi.com/post/python-yahoo-finance.

Stock Info

Using the attribute info we can extract information about the stock as a Python dictionary.

apple_info=apple.info apple_info
{'zip': '95014', 'sector': 'Technology', 'fullTimeEmployees': 100000, 'longBusinessSummary': 'Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. It also sells various related services. 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, HomePod, iPod touch, and other Apple-branded and third-party accessories. It also provides AppleCare support services; 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. In addition, the company offers various services, such as Apple Arcade, a game subscription 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 sells and delivers 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 founded in 1977 and is headquartered in Cupertino, California.', 'city': 'Cupertino', 'phone': '408-996-1010', 'state': 'CA', 'country': 'United States', 'companyOfficers': [], 'website': 'http://www.apple.com', 'maxAge': 1, 'address1': 'One Apple Park Way', 'industry': 'Consumer Electronics', 'previousClose': 125.06, 'regularMarketOpen': 124.68, 'twoHundredDayAverage': 127.63022, 'trailingAnnualDividendYield': 0.0065568527, 'payoutRatio': 0.1834, 'volume24Hr': None, 'regularMarketDayHigh': 124.85, 'navPrice': None, 'averageDailyVolume10Day': 69206814, 'totalAssets': None, 'regularMarketPreviousClose': 125.06, 'fiftyDayAverage': 129.17285, 'trailingAnnualDividendRate': 0.82, 'open': 124.68, 'toCurrency': None, 'averageVolume10days': 69206814, 'expireDate': None, 'yield': None, 'algorithm': None, 'dividendRate': 0.88, 'exDividendDate': 1620345600, 'beta': 1.203743, 'circulatingSupply': None, 'startDate': None, 'regularMarketDayLow': 123.13, 'priceHint': 2, 'currency': 'USD', 'trailingPE': 27.768038, 'regularMarketVolume': 74123095, 'lastMarket': None, 'maxSupply': None, 'openInterest': None, 'marketCap': 2061586137088, 'volumeAllCurrencies': None, 'strikePrice': None, 'averageVolume': 96252439, 'priceToSalesTrailing12Months': 6.3354278, 'dayLow': 123.13, 'ask': 123.52, 'ytdReturn': None, 'askSize': 1000, 'volume': 74123095, 'fiftyTwoWeekHigh': 145.09, 'forwardPE': 23.091589, 'fromCurrency': None, 'fiveYearAvgDividendYield': 1.34, 'fiftyTwoWeekLow': 80.195, 'bid': 123.47, 'tradeable': False, 'dividendYield': 0.0069999998, 'bidSize': 900, 'dayHigh': 124.85, 'exchange': 'NMS', 'shortName': 'Apple Inc.', 'longName': 'Apple Inc.', 'exchangeTimezoneName': 'America/New_York', 'exchangeTimezoneShortName': 'EDT', 'isEsgPopulated': False, 'gmtOffSetMilliseconds': '-14400000', 'quoteType': 'EQUITY', 'symbol': 'AAPL', 'messageBoardId': 'finmb_24937', 'market': 'us_market', 'annualHoldingsTurnover': None, 'enterpriseToRevenue': 6.613, 'beta3Year': None, 'profitMargins': 0.23451, 'enterpriseToEbitda': 21.557, '52WeekChange': 0.551998, 'morningStarRiskRating': None, 'forwardEps': 5.35, 'revenueQuarterlyGrowth': None, 'sharesOutstanding': 16687599616, 'fundInceptionDate': None, 'annualReportExpenseRatio': None, 'bookValue': 4.146, 'sharesShort': 94747255, 'sharesPercentSharesOut': 0.0057, 'fundFamily': None, 'lastFiscalYearEnd': 1601078400, 'heldPercentInstitutions': 0.58715, 'netIncomeToCommon': 76311003136, 'trailingEps': 4.449, 'lastDividendValue': 0.22, 'SandP52WeekChange': 0.35207164, 'priceToBook': 29.797396, 'heldPercentInsiders': 0.00066, 'nextFiscalYearEnd': 1664150400, 'mostRecentQuarter': 1616803200, 'shortRatio': 1.01, 'sharesShortPreviousMonthDate': 1618444800, 'floatShares': 16670609616, 'enterpriseValue': 2151866171392, 'threeYearAverageReturn': None, 'lastSplitDate': 1598832000, 'lastSplitFactor': '4:1', 'legalType': None, 'lastDividendDate': 1620345600, 'morningStarOverallRating': None, 'earningsQuarterlyGrowth': 1.101, 'dateShortInterest': 1620950400, 'pegRatio': 1.45, 'lastCapGain': None, 'shortPercentOfFloat': 0.0057, 'sharesShortPriorMonth': 127937929, 'impliedSharesOutstanding': None, 'category': None, 'fiveYearAverageReturn': None, 'regularMarketPrice': 123.54, 'logo_url': 'https://logo.clearbit.com/apple.com'}

We can get the 'country' using the key country

apple_info['country']
'United States'

Extracting Share Price

A share is the single smallest part of a company's stock that you can buy, the prices of these shares fluctuate over time. Using the history() method we can get the share price of the stock over a certain period of time. Using the period parameter we can set how far back from the present to get data. The options for period are 1 day (1d), 5d, 1 month (1mo) , 3mo, 6mo, 1 year (1y), 2y, 5y, 10y, ytd, and max.

apple_share_price_data = apple.history(period="max")

The format that the data is returned in is a Pandas DataFrame. With the Date as the index the share Open, High, Low, Close, Volume, and Stock Splits are given for each day.

apple_share_price_data.head()

We can reset the index of the DataFrame with the reset_index function. We also set the inplace paramter to True so the change takes place to the DataFrame itself.

apple_share_price_data.reset_index(inplace=True)

We can plot the Open price against the Date:

apple_share_price_data.plot(x="Date", y="Open")
<AxesSubplot:xlabel='Date'>
Image in a Jupyter notebook

Extracting Dividends

Dividends are the distribution of a companys profits to shareholders. In this case they are defined as an amount of money returned per share an investor owns. Using the variable dividends we can get a dataframe of the data. The period of the data is given by the period defined in the 'history` function.

apple.dividends
Date 1987-05-11 0.000536 1987-08-10 0.000536 1987-11-17 0.000714 1988-02-12 0.000714 1988-05-16 0.000714 ... 2020-05-08 0.205000 2020-08-07 0.205000 2020-11-06 0.205000 2021-02-05 0.205000 2021-05-07 0.220000 Name: Dividends, Length: 71, dtype: float64

We can plot the dividends overtime:

apple.dividends.plot()
<AxesSubplot:xlabel='Date'>
Image in a Jupyter notebook

Exercise

Now using the Ticker module create an object for AMD (Advanced Micro Devices) with the ticker symbol is AMD called; name the object amd.

amd = yf.Ticker('AMD')

Question 1 Use the key 'country' to find the country the stock belongs to.

amd.info['country']
'United States'

Question 2 Use the key 'sector' to find the sector the stock belongs to.

amd.info['sector']
'Technology'

Question 3 Find the max of the Volume column of AMD using the history function, set the period to max.

amd.history(period="max")['Volume'].max()
325058400