How to Pull Stock Data into your Python ProgramHow to Pull Stock Data into your Python Program

Grab Stock Data using Python Programming: yfinance

Gautamankul
4 min readApr 28, 2022

Rinu Gour TDS Editors Aman Kharwal

How to Pull Stock Data into your Python Program

Hey stock marketer’s today we are analysis How to Pull Stock Data into your Python Program before start trading in stock market, research about that particular company and analysis the data into graphical and chart way using python programming and download those company data into csv file also

Prerequisite:

  1. python3
  2. pandas
  3. matplotlib
  4. jupyter nootbook

Setup:

we’re install all prerequisite following packages which is helpful for analyze and predicate data .

$ sudo apt-get install python3$ python3 -m pip install pandas$ python3 -m pip insatll  matplotlib$ python3 -m pip install jupyterlab$ python3 -m pip install yfinance

How package’s work?

Pandas :It is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real-world data analysis in Python

Matplotlib: It is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.

Jupyter NoteBook: It is a powerful way to write and iterate on your Python code for data analysis. … It also allows Jupyter Notebook to support multiple languages. Jupyter Notebooks extend IPython through additional features, like storing your code and output and allowing you to keep markdown notes.

Yfinance: It aims to solve this problem by offering a reliable, threaded, and Pythonic way to download historical market data from Yahoo! finance.

Get Current stock Price of a Company :

Here we are getting current price ratio of AMAZON which is showing current and previous date close price.

import yfinance as yfstock_info = yf.Ticker('AMZN').info

market_price = stock_info['regularMarketPrice']previous_close_price = stock_info['regularMarketPreviousClose']print('market price ', market_price)print('previous close price ', previous_close_price)# output
# market price 3450
# previous close price 3457.17

Get Amazon one years stock market data’s representation………..

import matplotlib.pyplot as plt
import yfinance as yfdata = yf.Ticker("AMZN")
prices = data.history(period="1y")
print(prices)

Graphical representation using matploitlib…

import matplotlib.pyplot as plt
import yfinance as yfaaple = yf.Ticker("AMZN")prices = aaple.history(period="1y")prices['20d'] = prices['Close'].rolling(20).mean()prices['200d'] = prices['Close'].rolling(200).mean()prices[['Close','20d','200d']].plot()plt.title('Moving Averages Apple')

Calculate and Plot Cumulative Returns:

We can also use Pandas to calculate and plot Apple cumulative returns using the pct_change and cumsum methods.

Pct_change will calculate the daily returns. Then, we use consume method in order to get the cumulation of all daily returns included in our selected time period.

import matplotlib.pyplot as plt
import yfinance as yfaaple = yf.Ticker("AMZN")prices = aaple.history(period="1y")prices['daily_return'] = prices['Close'].pct_change()prices['cumulative_return'] = prices['daily_return'].cumsum()prices['cumulative_return'].plot()
plt.title('Cumulative Return Apple')

Comparing Prices for Multiple Companies:

We can also use yfinance to retrieve historical prices for multiple companies. This is perfect for comparing how companies are performing relative to others.

Similarly to the previous sections, we only need a few lines of code in order to retrieve all historical prices for all companies. Here, we use a for-loop in order to retrieve each of the stock prices. Then, we append them in a Python list and convert it into a Data Frame.

import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
stocks =['AAPL','MSFT','FB','GME','TSLA','AMZN']
stock_list = []
for stock in stocks:
returns = yf.Ticker(stock)
returns = returns.history(period="1y")
returns['returns'] = returns['Close'].pct_change()
returns.rename(columns={'returns': stock}, inplace=True)
returns = returns[stock]
stock_list.append(returns)
all_stock_returns =pd.DataFrame(stock_list).T
all_stock_returns

SO stocker’s analyze data and start trading in stock market’s if want to read more about market research Follow and support me!

Good Bye Marketer’s have a nice day !

--

--

Gautamankul

A Software Developer Engineer & Entrepreneur and along with i am a Buddhist.