0% found this document useful (0 votes)
8 views7 pages

Stock Price Analysis with Python

Uploaded by

mhiqbal20032003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views7 pages

Stock Price Analysis with Python

Uploaded by

mhiqbal20032003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

5/7/23, 11:35 AM Stock Price Analysis With Python - Analytics Vidhya

Stock Price Analysis With Python 

×
50+ Exciting Industry Projects to become a Full-Stack Data Scientist
Download Projects

Home

Maverick 01 — Published On July 11, 2021 and Last Modified On May 5th, 2023
Beginner Data Visualization Datetime Python Time Series

Stock price analysis with Python is crucial for investors to understand the risk of investing in the stock market. A company’s
stock prices reflect its evaluation and performance, which influences the demand and supply in the market. Technical analysis of
the stock is a vast field, and we will provide an overview of it in this article. By analyzing the stock price with Python, investors
can determine when to buy or sell the stock. This article will be a starting point for investors who want to analyze the stock
market and understand its volatility. So, let’s dive into the stock price analysis with Python.

Table of contents
Libraries Used in Stock Price Analysis With Python
Data Description
Exploratory Analysis for Stock Price Analysis With Python
Moving Averages for Stock Price Analysis With Python
Scattered Plot Matrix
Percentage Increase in Stock Value
Conclusion

Libraries Used in Stock Price Analysis With Python


The following are the libraries required to be installed beforehand which can easily be downloaded with the help of the pip
function. A brief description of the Library’s name and its application is provided below

Library Application
Yahoo Finance To download stock data
Pandas To handle data frames in python
Numpy Numerical Python
Matplotlib Plotting graphs

We use cookies on Analytics Vidhya websites to deliver our services, analyze web traffic, and improve your experience on the site. By using Analytics Vidhya, you

agree to our Privacy Policy and Terms of Use. Accept

[Link] 1/7
5/7/23, 11:35 AM Stock Price Analysis With Python - Analytics Vidhya

import pandas as pd
Stock Price Analysis With Python
import datetime

import numpy as np

import [Link] as plt

from [Link] import scatter_matrix

!pip install yfinance

import yfinance as yf

%matplotlib inline

Data Description
We have downloaded the daily stock prices data using the Yahoo finance API functionality. It’s a five-year data capturing Open,
High, Low, Close, and Volume

Open: The price of the stock when the market opens in the morning
Close: The price of the stock when the market closed in the evening
High: Highest price the stock reached during that day
Low: Lowest price the stock is traded on that day
Volume: The total amount of stocks traded on that day
Here, we will take the Example of three companies TCS, Infosys, and Wipro which are the industry leaders in providing IT
services.

start = "2014-01-01"
end = '2019-1-01'
tcs = [Link]('TCS',start,end)
infy = [Link]('INFY',start,end)
wipro = [Link]('[Link]',start,end)

Exploratory Analysis for Stock Price Analysis With Python


Python Code:

We use cookies on Analytics Vidhya websites to deliver our services, analyze web traffic, and improve your experience on the site. By using Analytics Vidhya, you

agree to our Privacy Policy and Terms of Use. Accept

[Link] 2/7
5/7/23, 11:35 AM Stock Price Analysis With Python - Analytics Vidhya

The above
Stock graph
Price is the representation
Analysis With Python of open stock prices for these three companies via line graph by leveraging matplotlib
library in python. The Graph clearly shows that the prices of Wipro is more when comparing it to other two companies but we
are not interested in the absolute prices for these companies but wanted to understand how these stock fluctuate with time.

tcs['Volume'].plot(label = 'TCS', figsize = (15,7))


infy['Volume'].plot(label = "Infosys")
wipro['Volume'].plot(label = 'Wipro')
[Link]('Volume of Stock traded')
[Link]()

The Graph shows the volume traded by these companies which clearly shows that stocks of Infosys are traded more compared
to other IT stocks.

#Market Capitalisation
tcs['MarktCap'] = tcs['Open'] * tcs['Volume']
infy['MarktCap'] = infy['Open'] * infy['Volume']
wipro['MarktCap'] = wipro['Open'] * wipro['Volume']
tcs['MarktCap'].plot(label = 'TCS', figsize = (15,7))
infy['MarktCap'].plot(label = 'Infosys')
wipro['MarktCap'].plot(label = 'Wipro')
[Link]('Market Cap')
[Link]()

We use cookies on Analytics Vidhya websites to deliver our services, analyze web traffic, and improve your experience on the site. By using Analytics Vidhya, you

agree to our Privacy Policy and Terms of Use. Accept

[Link] 3/7
5/7/23, 11:35 AM Stock Price Analysis With Python - Analytics Vidhya

Stock Price Analysis With Python

Only volume or stock prices do not provide a comparison between companies. In this case, we have plotted a graph for Volume *
Share price to better compare the companies. As we can clearly see from the graph that Wipro seems to be traded on a higher
side.

Moving Averages for Stock Price Analysis With Python


As we know the stock prices are highly volatile and prices change quickly with time. To observe any trend or pattern we can
take the help of a 50-day 200-day average

tcs['MA50'] = tcs['Open'].rolling(50).mean()
tcs['MA200'] = tcs['Open'].rolling(200).mean()
tcs['Open'].plot(figsize = (15,7))
tcs['MA50'].plot()
tcs['MA200'].plot()

Scattered Plot Matrix


data = [Link]([tcs['Open'],infy['Open'],wipro['Open']],axis = 1)
[Link] = ['TCSOpen','InfosysOpen','WiproOpen']
scatter_matrix(data, figsize = (8,8), hist_kwds= {'bins':250})

We use cookies on Analytics Vidhya websites to deliver our services, analyze web traffic, and improve your experience on the site. By using Analytics Vidhya, you

agree to our Privacy Policy and Terms of Use. Accept

[Link] 4/7
5/7/23, 11:35 AM Stock Price Analysis With Python - Analytics Vidhya

Stock Price Analysis With Python

The above graph is the combination of histograms for each company and a subsequent scattered plot taking two companies’
stocks at a time. From the graph, we can clearly figure out that Wipro stocks are loosely showing a linear correlation with
Infosys.

Percentage Increase in Stock Value


A percentage increase in stock value is the change in stock comparing that to the previous day. The bigger the value either
positive or negative the volatile the stock is.

#Volatility
tcs['returns'] = (tcs['Close']/tcs['Close'].shift(1)) -1
infy['returns'] = (infy['Close']/infy['Close'].shift(1))-1
wipro['returns'] = (wipro['Close']/wipro['Close'].shift(1)) - 1
tcs['returns'].hist(bins = 100, label = 'TCS', alpha = 0.5, figsize = (15,7))
infy['returns'].hist(bins = 100, label = 'Infosysy', alpha = 0.5)
wipro['returns'].hist(bins = 100, label = 'Wipro', alpha = 0.5)
[Link]()

It is clear from the graph that the percentage increase in stock price histogram for TCS is the widest which indicates the stock of
TCS is the most volatile among the three companies compared.
We use cookies on Analytics Vidhya websites to deliver our services, analyze web traffic, and improve your experience on the site. By using Analytics Vidhya, you

agree to our Privacy Policy and Terms of Use. Accept

[Link] 5/7
5/7/23, 11:35 AM Stock Price Analysis With Python - Analytics Vidhya

Conclusion
Stock Price Analysis With Python
The above analysis can be used to understand a stock’s short-term and long-term behaviour. A decision support system can be
created which stock to pick from industry for low-risk low gain or high-risk high gain depending on the risk apatite of the
investor.

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

blogathon python stock price Time Series

About the Author


Maverick 01

Our Top Authors

view more

 

Download
Analytics Vidhya App for the Latest blog/Article

Previous Post Next Post

Roadmap To Clear Azure DP 100 -Designing and An Intuitive and Easy Guide to Python Sets- Must for
Implementing a Data Science Solution on Azure Becoming Data Science Professional

Leave a Reply
Your email address will not be published. Required fields are marked *

Comment

Name* Email*

We use cookies on Analytics Vidhya websites to deliver our services, analyze web traffic, and improve your experience on the site. By using Analytics Vidhya, you
Website agree to our Privacy Policy and Terms of Use. Accept

[Link] 6/7
5/7/23, 11:35 AM Stock Price Analysis With Python - Analytics Vidhya

Notify me of follow-up comments by email.


Stock Price Analysis With Python
Notify me of new posts by email.

Submit

Top Resources

Geoffrey Hinton, Godfather of AI Leaves Google, Warns of OpenAI with Andrew Ng Launches Course on Prompt
Potential.. Engineering (Limited Free..

Yana Khare - MAY 01, 2023 Yana Khare - APR 28, 2023

Make Money While Sleeping: Side Hustles to Generate Understand Random Forest Algorithms With Examples
Passive Income.. (Updated 2023)

Aayush Tyagi - APR 27, 2023 Sruthi E R - JUN 17, 2021

Analytics Vidhya Data Scientists


About Us Blog

Our Team Hackathon

Careers Discussions
Download App Contact us Apply Jobs

Companies Visit us
Post Jobs    

Trainings

Hiring Hackathons

Advertising

© Copyright 2013-2023 Analytics Vidhya. Privacy Policy Terms of Use Refund Policy

We use cookies on Analytics Vidhya websites to deliver our services, analyze web traffic, and improve your experience on the site. By using Analytics Vidhya, you

agree to our Privacy Policy and Terms of Use. Accept

[Link] 7/7

Common questions

Powered by AI

Market capitalization is determined by the stock's current market price multiplied by the total number of outstanding shares. It serves as a significant metric for comparing company sizes and growth potential within the same industry. It reflects investor perceptions of a company's future prospects and overall market value. By comparing market capitalizations, investors can gauge the relative size of companies and assess which firms dominate the industry landscape .

Historical stock price data exploration assists in identifying patterns and trends that can be extrapolated to forecast future movements. In volatile sectors like IT, past price movements and patterns can highlight market reactions to similar conditions, aiding in predictions. Analysts can also compare responses to historical events to assess how similar future occurrences might impact stock performance, though this requires accounting for current contextual variables .

Differentiating between short-term and long-term trends is crucial as it informs investment strategy; short-term trends help in tactical decisions like timing the market entry or exits, while long-term trends provide guidance for strategic asset allocation and identifying growth potentials. Short-term trends may result from transient factors, whereas long-term trends are indicative of the underlying business health and broader economic conditions. This distinction allows investors to tailor strategies to their risk profiles and investment goals .

Moving averages help in smoothing out the short-term fluctuations in stock prices to highlight longer-term trends. The 50-day moving average is used to identify the immediate trend, while the 200-day moving average is typically used to confirm the long-term trend. The rationale behind using these specific timeframes is that they capture different market behaviors — with 50-day giving insight into a market's short-term momentum and 200-day providing a broader perspective, often used to determine potential changes in the overarching trend .

Comparing volume-traded graphs can provide insights into the relative liquidity and trading interest for each stock over time. For TCS, Infosys, and Wipro, the graph shows that Infosys experiences the highest trading volume, suggesting greater investor interest or market activity compared to TCS and Wipro. This can indicate Infy's stronger market momentum or more speculative trading behavior, possibly leading to higher liquidity for the stock .

Key tools and libraries used for stock price analysis with Python include Yahoo Finance (yfinance) for downloading stock data, Pandas for data manipulation and handling data frames, Numpy for numerical operations, and Matplotlib for plotting graphs. These libraries are selected because they provide comprehensive functionality needed to extract, manage, analyze, and visualize stock data effectively, enabling end-to-end stock analysis .

A histogram is significant for visualizing the percentage increases of stocks as it displays the distribution of percentage changes over a period, making it easier to identify the volatility and frequency of particular returns. Unlike line or bar charts, histograms highlight the probability distribution, allowing for an assessment of consistency and extremes in stock returns. This makes them particularly useful for analyzing volatility and identifying patterns in stock behavior .

The percentage increase in stock value is an indicator of volatility; greater changes, whether positive or negative, signify higher volatility. A stock's volatility is a measure of the frequency and magnitude of price movements. For TCS, the histogram of the percentage increase is the widest among compared companies, indicating that its stock is the most volatile. This suggests that TCS has experienced significant day-to-day price fluctuations during the analyzed period .

The scatter plot matrix provides a visual representation of the relationships between stock prices of different companies, allowing for the identification of correlations. This visualization approach can help determine whether the stocks move in synchronization (positive correlation) or inversely (negative correlation). In the case of Wipro and Infosys, the scatter plot indicated a loose linear correlation, suggesting that their stock prices tend to move in a somewhat related manner over time, but not perfectly in sync .

Investors may consider absolute stock prices to understand the immediate buy-in cost for an investment, while market capitalization provides broader insight into a company's value and standing within the industry. Together, these metrics allow investors to assess both the cost of investment and the relative size and position of a company compared to its peers, which is particularly useful in the competitive and rapidly evolving IT industry .

You might also like