# Stock Price Analysis With Python

Maverick 01 05 May, 2023 â€¢ 4 min read

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.

## 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

```import pandas as pd

import datetime

import numpy as np

import matplotlib.pyplot as plt

from pandas.plotting 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'

## Exploratory Analysis for Stock Price Analysis With Python

Python Code:

The above graph is the representation 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')
plt.legend()```

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')
plt.title('Market Cap')
plt.legend()```

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 = pd.concat([tcs['Open'],infy['Open'],wipro['Open']],axis = 1)
data.columns = ['TCSOpen','InfosysOpen','WiproOpen']
scatter_matrix(data, figsize = (8,8), hist_kwds= {'bins':250})```

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)
plt.legend()```

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.

## Conclusion

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.

Maverick 01 05 May 2023

27 Lessons
4.86

70 Lessons
5