Analyzing Stock Data with Yahoo Finance for Beginners (2024)

Analyzing stock data can be a powerful tool for investors, traders, or anyone interested in understanding the financial markets. Yahoo Finance is a popular platform that provides free access to a wealth of financial data, making it an excellent resource for beginners. In this article, we'll guide you through a simple analysis project using Python and Yahoo Finance. Even if you have no prior experience with programming, we'll break down the steps to help you get started.

Step project

Data

Summarize the Data Frames

Comparison of Stocks

Market Capitalization

Moving Averages

Volatility and Stability

Correlations

Generate Heatmaps

Import the Libraries and Data

import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport yfinance as yffrom pandas.plotting import scatter_matrix 

We will be working with Microsoft, Adobe, SalesForce, and Oracle. The time period is from 1st January 2020 to 31st October 2033.

start = "2020-01-01"end = "2023-10-31"msft = yf.download("MSFT", start, end)crm = yf.download("CRM", start, end)orcl = yf.download("ORCL", start, end)adbe = yf.download("ADBE", start, end) 

Summarize the Data Frames

# Obtain the necessary information for each stock def get_info(dataframe) : stock_info = pd.DataFrame({ 'Datatype' : dataframe.dtypes, # Data types of columns 'Total_Element': dataframe.count(), # Total elements in columns 'Null_Count': dataframe.isnull().sum(), # Total null values in columns 'Null_Percentage': dataframe.isnull().sum()/len(dataframe) * 100 # Percentage of null values }) return stock_info# Call the function for each stockget_info(msft)get_info(crm)get_info(orcl)get_info(adbe) 
Analyzing Stock Data with Yahoo Finance for Beginners (1)
# Describe the numerical data for each stockmsft.describe()crm.describe()orcl.describe()adbe.describe() 
Analyzing Stock Data with Yahoo Finance for Beginners (2)

Comparison of Stocks

# Find the average of the volume of stocks traded over time for each stock.# Round off the value.msft_vol_avg = round(msft["Volume"].mean())crm_vol_avg = round(crm["Volume"].mean())orcl_vol_avg = round(orcl["Volume"].mean())adbe_vol_avg = round(adbe["Volume"].mean())# Run this code cell to convert the results into an arrayvol_avg = np.array([msft_vol_avg, crm_vol_avg, orcl_vol_avg, adbe_vol_avg])# Create the pie chartmylabels = ["Microsoft", "SalesForce", "Oracle", "Adobe"]myexplode = [0.2, 0, 0, 0] # To create an exploding wedgeplt.pie(vol_avg, labels = mylabels, explode = myexplode, shadow = True, autopct="%.2f")plt.show() 
Analyzing Stock Data with Yahoo Finance for Beginners (3)

Visualize the Trade Volume Over Time

# Perform the visualization in a single graphmsft['Volume'].plot(label = 'Microsoft', figsize = (16,4))crm['Volume'].plot(label = 'SalesFoce')orcl['Volume'].plot(label = 'Oracle')adbe['Volume'].plot(label = 'Adobe')plt.title('Volume of Stock traded')plt.legend() 
Analyzing Stock Data with Yahoo Finance for Beginners (4)

Microsoft is almost consistently traded the most, with plenty of variation in its trade volume throughout the years. Oracle and SaleForce come next, also with plenty of variation throughout the years, and, at times, going higher than Microsoft. Finally, we have Adobe with minimal variation in its trade volume, and located consistently below its 3 competitors.

Find the Highest Price of Stocks Traded with Time

msft['High'].plot(label = 'Microsoft', figsize = (16,8))crm['High'].plot(label = 'SalesFoce')orcl['High'].plot(label = 'Oracle')adbe['High'].plot(label = 'Adobe')plt.title('Highest Price Reached for Each Stock traded')plt.legend() 
Analyzing Stock Data with Yahoo Finance for Beginners (5)

Find the Lowest Prices of Stocks Traded with Time

msft['Low'].plot(label = 'Microsoft', figsize = (16,8))crm['Low'].plot(label = 'SalesFoce')orcl['Low'].plot(label = 'Oracle')adbe['Low'].plot(label = 'Adobe')plt.title('Lowest Price Reached for Each Stock traded')plt.legend() 
Analyzing Stock Data with Yahoo Finance for Beginners (6)

Find the Open Price of Stocks Traded with Time

msft['Open'].plot(label = 'Microsoft', figsize = (16,8))crm['Open'].plot(label = 'SalesFoce')orcl['Open'].plot(label = 'Oracle')adbe['Open'].plot(label = 'Adobe')plt.title('Open Price for Each Stock traded')plt.legend() 
Analyzing Stock Data with Yahoo Finance for Beginners (7)

Market Capitalization

Market capitalization is a simple but essential concept in finance that represents the total value of a publicly traded company's outstanding shares of stock. In other words, it is the total worth of a company as perceived by the stock market.

To calculate market capitalization, you multiply the current market price of one share of a company's stock by the total number of outstanding shares. It's a straightforward equation:

Market Capitalization = Current Stock Price per Share x Total Outstanding Shares

Market capitalization provides a quick and easy way to gauge the size of a company and its relative importance in the financial markets. It is often used to categorize companies into various size classes:

1. Large-Cap: Companies with a market capitalization typically exceeding $10 billion.

2. Mid-Cap: Companies with a market capitalization between $2 billion and $10 billion.

3. Small-Cap: Companies with a market capitalization below $2 billion.

msft['M_Cap'] = msft['Open'] * msft['Volume']crm['M_Cap'] = crm['Open'] * crm['Volume']orcl['M_Cap'] = orcl['Open'] * orcl['Volume']adbe['M_Cap'] = adbe['Open'] * adbe['Volume']msft['M_Cap'].plot(label = 'Microsoft', figsize = (15,7))crm['M_Cap'].plot(label = 'SalesForce')orcl['M_Cap'].plot(label = 'Oracle')adbe['M_Cap'].plot(label = 'Adobe')plt.title('Market Cap')plt.legend() 
Analyzing Stock Data with Yahoo Finance for Beginners (8)

For the given data, we will find that Microsoft and SalesForce are traded more compared to Adobe and Oracle.

Recommended by LinkedIn

The Digital Rolodex Helen Wall 1 year ago
Looker Studio /Google Data Studio Complete Advanced… Free Online Courses With Printable Certificates 11 months ago
Data as a Power to Inform Decisions in Business and… Leon Gordon 1 year ago

Thus, we can conclude that investing in Microsoft and SalesForce would provide a lower risk, with greater returns over time.

Moving Averages

Moving averages are a fundamental tool in finance used to smooth out price data and identify trends. They provide a simple and effective way to analyze the historical performance of a stock, currency, or any financial asset.

In essence, a moving average calculates the average price of an asset over a specific period of time and continually updates this average as new data becomes available. This "moving" average helps reduce noise and fluctuations in price data, making it easier to spot trends and patterns.

There are two main types of moving averages:

1. Simple Moving Average (SMA): This type calculates the average price over a fixed number of periods. For example, a 50-day SMA would add up the closing prices of the last 50 days and divide by 50 to get the average.

2. Exponential Moving Average (EMA): The EMA gives more weight to recent prices, making it more responsive to recent changes. It's often favored when traders want to react quickly to market movements.

Moving averages can be used for various purposes, such as identifying trends, determining support and resistance levels, and generating buy or sell signals. When the current price crosses above or below a moving average, it may signal a change in the asset's trend.

msft['MA50'] = msft['Open'].rolling(50).mean()msft['MA200'] = msft['Open'].rolling(200).mean()crm['MA50'] = crm['Open'].rolling(50).mean()crm['MA200'] = crm['Open'].rolling(200).mean()orcl['MA50'] = orcl['Open'].rolling(50).mean()orcl['MA200'] = orcl['Open'].rolling(200).mean()adbe['MA50'] = adbe['Open'].rolling(50).mean()adbe['MA200'] = adbe['Open'].rolling(200).mean()# Plot them together to compare themfigure, axes = plt.subplots(2, 2, figsize = (15, 10))figure.suptitle('Moving Averages for Microsoft, SalesForce, Oracle, and Adobe')axes[0,0].set_title('Microsoft')axes[0,1].set_title('SalesForce,')axes[1,0].set_title('Oracle')axes[1,1].set_title('Adobe')msft['MA50'].plot(ax=axes[0, 0])msft['MA200'].plot(ax=axes[0, 0])msft['Open'].plot(ax=axes[0, 0])crm['MA50'].plot(ax=axes[0, 1])crm['MA200'].plot(ax=axes[0, 1])crm['Open'].plot(ax=axes[0, 1])adbe['MA50'].plot(ax=axes[1, 0])adbe['MA200'].plot(ax=axes[1, 0])adbe['Open'].plot(ax=axes[1, 0])orcl['MA50'].plot(ax=axes[1, 1])orcl['MA200'].plot(ax=axes[1, 1])orcl['Open'].plot(ax=axes[1, 1]) 
Analyzing Stock Data with Yahoo Finance for Beginners (12)

Volatility and Stability

Volatility and stability are two contrasting concepts in the world of finance that describe the degree of uncertainty or risk associated with an asset's price or the financial system as a whole.

Volatility:

- Volatility refers to the degree of price fluctuations in a financial asset, such as a stock, currency, or commodity.

- High volatility implies that the price of the asset can change rapidly and dramatically over a short period.

- Low volatility suggests that the price changes are relatively steady and minimal.

- Volatility is often measured using indicators like the standard deviation of price returns or the VIX (Volatility Index).

Stability:

- Stability, on the other hand, describes a situation where prices or the financial system remain relatively constant and predictable over time.

- It implies a lower level of risk and uncertainty.

- Stability is usually preferred by long-term investors and is often associated with more established and less speculative assets.

Compare Volatility and Stability

Finding the volatility / stability for each of the stocks

msft['returns'] = (msft['Close']/msft['Close'].shift(1)) -1crm['returns'] = (crm['Close']/crm['Close'].shift(1)) -1orcl['returns'] = (orcl['Close']/orcl['Close'].shift(1)) -1adbe['returns'] = (adbe['Close']/adbe['Close'].shift(1)) -1# Visualize the results.figure, axes = plt.subplots(2, 2, figsize = (15, 10))figure.suptitle('Stability and Volatility for Microsoft, SalesForce, Oracle, and Adobe')axes[0,0].set_title('Microsoft')axes[0,1].set_title('SalesForce')axes[1,0].set_title('Oracle')axes[1,1].set_title('Adobe')msft['returns'].hist(bins = 100, label = 'Microsoft', alpha = 0.5, ax=axes[0, 0])crm['returns'].hist(bins = 100, label = 'SalesForce', alpha = 0.5, ax=axes[0, 1])orcl['returns'].hist(bins = 100, label = 'Oracle', alpha = 0.5, ax=axes[1, 0])adbe['returns'].hist(bins = 100, label = 'Adobe', alpha = 0.5, ax=axes[1, 1]) 
Analyzing Stock Data with Yahoo Finance for Beginners (13)

Comparing the volatility / stability for all the stocks

msft['returns'] = (msft['Close']/msft['Close'].shift(1)) -1crm['returns'] = (crm['Close']/crm['Close'].shift(1))-1orcl['returns'] = (orcl['Close']/orcl['Close'].shift(1)) - 1adbe['returns'] = (adbe['Close']/adbe['Close'].shift(1)) - 1msft['returns'].hist(bins = 100, label = 'Microsoft', alpha = 0.5, figsize = (15,7))crm['returns'].hist(bins = 100, label = 'SalesForce', alpha = 0.5)orcl['returns'].hist(bins = 100, label = 'Oracle', alpha = 0.5)adbe['returns'].hist(bins = 100, label = 'Adobe', alpha = 0.5)plt.suptitle('Comparing the volatility / stability for all the stocks')plt.legend() 
Analyzing Stock Data with Yahoo Finance for Beginners (14)

Correlations

Correlations refer to the statistical relationship or connection between two or more variables. In finance and investing, correlations are often used to understand how different financial assets, such as stocks, bonds, or commodities, move in relation to each other.

Positive Correlation: When two variables have a positive correlation, it means that they tend to move in the same direction. If one variable goes up, the other is likely to go up as well. For example, if the stock market rises, the prices of many individual stocks also tend to rise, showing a positive correlation.

Negative Correlation: A negative correlation exists when two variables move in opposite directions. If one variable goes up, the other tends to go down. An example of negative correlation is when the price of a particular asset, like gold, rises when the value of the U.S. dollar falls.

Correlations are expressed as a value between -1 and 1

  • A correlation of 1 means a perfect positive relationship.
  • A correlation of -1 means a perfect negative relationship.
  • A correlation of 0 suggests no significant relationship between the variables.

# Correlation table for Stock 1msft_corr = msft.corr()# Correlation table for Stock 2crm_corr = crm.corr()# Correlation table for Stock 3orcl_corr = orcl.corr()# Correlation table for Stock 4adbe_corr = adbe.corr()adbe_corr 
Analyzing Stock Data with Yahoo Finance for Beginners (15)

Generate Heatmaps

# Correlation table for Stock 1msft_corr = msft.corr()# Correlation table for Stock 2crm_corr = crm.corr()# Correlation table for Stock 3orcl_corr = orcl.corr()# Correlation table for Stock 4adbe_corr = adbe.corr()adbe_corr 
Analyzing Stock Data with Yahoo Finance for Beginners (16)
# Create a 2x2 grid of subplotsfig, axes = plt.subplots(2, 2, figsize=(16, 16))# Plot heatmap for Stock 1sns.heatmap(msft_corr, annot=True, ax=axes[0, 0])axes[0, 0].set_title('Microsoft')# Plot heatmap for Stock 2sns.heatmap(crm_corr, annot=True, ax=axes[0, 1])axes[0, 1].set_title('SalesForce')# Plot heatmap for Stock 3sns.heatmap(orcl_corr, annot=True, ax=axes[1, 0])axes[1, 0].set_title('Oracle')# Plot heatmap for Stock 4sns.heatmap(adbe_corr, annot=True, ax=axes[1, 1])axes[1, 1].set_title('Adobe')# Adjust layoutplt.tight_layout()plt.show() 
Analyzing Stock Data with Yahoo Finance for Beginners (17)

Conclusion:

This beginner-friendly project demonstrates how to analyze stock data using Yahoo Finance and Python. You've learned how to fetch historical data, perform basic analyses, and create simple visualizations. As you become more comfortable with Python and data analysis, you can explore more advanced techniques and strategies for making informed investment decisions. The world of financial analysis is vast, so don't hesitate to explore further and expand your knowledge. Happy analyzing!

Example code 👇

Analyzing Stock Data with Yahoo Finance for Beginners (2024)

FAQs

How to use Yahoo Finance for stock analysis? ›

Go to Yahoo Finance. Enter a company name or ticker symbol in the "Search" bar. Select a quote from the search list. Click the Research Reports tab to find Research Reports.

How to analyze a stock for beginners? ›

A very, very basic example of stock analysis would include looking at a stock's share price, comparing it to its historical averages and moving averages, overall market conditions, and looking at the company's financial statements to try and gauge where it might move next.

How do you read a stock chart for beginners? ›

Each trading day is represented as a bar on the chart with the open, high, low and closing prices. The length of the bar shows the stock's price range for that day, with the top of the bar representing the highest price and the bottom the lowest price for the trading day.

How to use Yahoo Finance stock screener? ›

From a mobile browser:
  1. Sign in to Yahoo Finance.
  2. Tap the Menu icon .
  3. Tap Screeners.
  4. Tap Saved Screeners.
  5. Tap Create New Screener.
  6. Select screener type.
  7. Enter your screening criteria.
  8. Tap Find Stocks.

How do I scrape stock data from Yahoo Finance? ›

Five Methods of YF Scraping
  1. Steps for Manual Scraping.
  2. Step 1: Navigate to the Yahoo Finance website. ...
  3. Step 2: Search for the data you're interested in. ...
  4. Step 3: Navigate to the Relevant Page. ...
  5. Step 4: Copy the Data. ...
  6. Step 5: Paste the Data. ...
  7. Step 6: Repeat as Needed. ...
  8. Steps in Scraping with Browser Extensions.
Aug 15, 2023

Is scraping Yahoo Finance legal? ›

In short, YES. Most of the data available on the Yahoo Finance website is open-source and public information.

Where does Yahoo Finance get its stock data? ›

Company and Fund Data Providers

US IPO data is provided by NYSE and NASDAQ. Upgrades and downgrades provided by Benzinga. Sustainability data provided by Sustainalytics and Morningstar.

How do I use Yahoo Finance data in Excel? ›

How to sync Yahoo Finance with Excel Using ETL Tool by Coupler.io?
  1. Select GET in the HTTP method. ...
  2. After that, connect your Microsoft OneDrive account and select the Workbook and Sheet where you want to export the Yahoo Finance data. ...
  3. Finally, click on the Run importer button to launch the Yahoo Finance export to Excel.

How to read stocks for dummies? ›

Open: This amount refers to where the stock's price opened for trading on that given day. High/low: These numbers are the highest and lowest prices that the stock traded at on that day. Market cap: This figure refers to the company's market capitalization, or the value of all the company's outstanding shares.

Which chart is best for stock analysis? ›

Line charts provide a simplified view of an asset's price movement by connecting closing prices with a line. To enhance your analysis, think about using a line chart when you want to see something over time as it's a great tool for trend analysis over a period.

What is the easiest way to explain stocks? ›

How do stocks work? A stock represents a share in the ownership of a company, including a claim on the company's earnings and assets. As such, stockholders are partial owners of the company. When the value of the business rises or falls, so does the value of the stock.

How do I compare stocks in Yahoo Finance? ›

Go to Yahoo Finance. Search for and select a symbol you want to compare. In the upper left, click Comparison. Search for and select another symbol to compare.

How do I track stocks on Yahoo Finance? ›

All transactions, including share lots and dividends, can be tracked so you always know what you've bought, sold, etc.
  1. Click on the Portfolio you want to add a transaction to.
  2. Click the Menu arrow. ...
  3. Click the Transaction tab.
  4. Click Add a transaction.
  5. Fill in the requested information.
  6. Click Save transaction.

How do I use Yahoo Finance indicators? ›

Add indicators to charts in Yahoo Finance for Web
  1. Go to Yahoo Finance.
  2. Enter a company name or ticker symbol in the "Search" bar.
  3. Select a quote from the search list.
  4. Above the chart, click Advanced Chart .
  5. Click Indicators.
  6. Select an indicator type or search indicators.
  7. Choose your indicator parameters.

How do I extract financials from Yahoo Finance? ›

Export and import portfolio data in Yahoo Finance
  1. Sign in to Yahoo Finance.
  2. Click My Portfolio.
  3. Click the portfolio name of the list you want to export.
  4. Click Export.
  5. Open the Downloads folder on your computer to find the exported file named "quotes. csv."

Top Articles
VeChain (VET) for Beginners: How It Works, Use Cases, and Coin | Tangem Blog
Make the most of retirement with us | Vanguard
Nybe Business Id
Places 5 Hours Away From Me
Craigslist Free En Dallas Tx
Is pickleball Betts' next conquest? 'That's my jam'
Mopaga Game
Us 25 Yard Sale Map
Lantana Blocc Compton Crips
Ave Bradley, Global SVP of design and creative director at Kimpton Hotels & Restaurants | Hospitality Interiors
Sarpian Cat
Https E24 Ultipro Com
Salem Oregon Costco Gas Prices
St Maries Idaho Craigslist
De beste uitvaartdiensten die goede rituele diensten aanbieden voor de laatste rituelen
Aspen Mobile Login Help
Zoe Mintz Adam Duritz
라이키 유출
Amazing deals for Abercrombie & Fitch Co. on Goodshop!
Bible Gateway passage: Revelation 3 - New Living Translation
At 25 Years, Understanding The Longevity Of Craigslist
Cor Triatriatum: Background, Pathophysiology, Epidemiology
Cable Cove Whale Watching
Evil Dead Rise Ending Explained
Myaci Benefits Albertsons
*!Good Night (2024) 𝙵ull𝙼ovie Downl𝚘ad Fr𝚎e 1080𝚙, 720𝚙, 480𝚙 H𝙳 HI𝙽DI Dub𝚋ed Fil𝙼yz𝚒lla Isaidub
Our Leadership
Datingscout Wantmatures
R3Vlimited Forum
Half Inning In Which The Home Team Bats Crossword
RFK Jr., in Glendale, says he's under investigation for 'collecting a whale specimen'
Great Clips On Alameda
67-72 Chevy Truck Parts Craigslist
Royals op zondag - "Een advertentie voor Center Parcs" of wat moeten we denken van de laatste video van prinses Kate?
Covalen hiring Ai Annotator - Dutch , Finnish, Japanese , Polish , Swedish in Dublin, County Dublin, Ireland | LinkedIn
Empire Visionworks The Crossings Clifton Park Photos
Mckinley rugzak - Mode accessoires kopen? Ruime keuze
Walgreens Agrees to Pay $106.8M to Resolve Allegations It Billed the Government for Prescriptions Never Dispensed
Oriellys Tooele
Dr Adj Redist Cadv Prin Amex Charge
Fifty Shades Of Gray 123Movies
Colorado Parks And Wildlife Reissue List
How Big Is 776 000 Acres On A Map
Cch Staffnet
Devotion Showtimes Near Showplace Icon At Valley Fair
Cara Corcione Obituary
Food and Water Safety During Power Outages and Floods
All Buttons In Blox Fruits
Strawberry Lake Nd Cabins For Sale
Okta Hendrick Login
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 6510

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.