FREE Yahoo Finance : Get Historical Stock Data in Python

kamal chanchal
3 min readDec 14, 2023

šŸ“ˆ Yahoo Finance is a widely used financial platform that provides a range of financial information and services, including historical stock data. Historical stock data is important for several reasons, and Yahoo Finance serves as a valuable resource for investors, researchers, and analysts in this regard. Investors use historical stock data to analyze a stockā€™s performance over time.

As we explore the structure of Yahoo Finance and its seamless integration with Python.

Yahoo Finance Python Package

Yahoo Finance:

In this post, weā€™ll will process , accessing historical stock data using Python.

Understanding the Data Dimensions:

The versatility of Yahoo Financeā€™s historical data downloads included intraday, weekly, and monthly time frames. This flexibility allows developers and analysts to tailor their data retrieval to match specific research needs.

Performing Analysis on Nifty Index Historical Data

Decoding the Data Elements:

The core components of stock market history are encapsulated in the Date, Open, High, Low, Close, Adj Close, and Volume parameters. These elements form the backbone of our analysis and provide a comprehensive view of a stockā€™s historical performance.

class Quote:
mDate = "Date"
mOpen = "Open"
mHigh = "High"
mLow = "Low"
mClose = "Close"
mAdjClose = "Adj Close"
mVolume = "Volume"

Key Features of the Python Class ā€” Quote:

  • Date: Capturing the chronological aspect of stock data.
  • Open, High, Low, Close: Diving into the daily fluctuations in stock prices.
  • Adj Close: Understanding adjusted closing prices for accurate analysis.
  • Volume: Gaining insights into trading volumes, a crucial aspect for market evaluation.

Python Code Implementation:

  • Introducing Analysis_Index class, an embodiment of Object-Oriented Programming (OOP) principles.
  • Code walkthrough: The class constructor, data storage setup, and the process of fetching historical stock data for a specified trading symbol.

Include Library in Python:

import pandas as pd
import yfinance as yf

class Analysis_Index :

def __init__( self , TradingSymbol ) :
print( "Constructor Called" )

print( "Creating Storage to Store Historical (Financial) Data" )
self.df_history_data = pd.DataFrame(
columns = [ Quote.mDate , Quote.mOpen , Quote.mHigh , Quote.mLow , Quote.mClose , Quote.mAdjClose ,
Quote.mVolume ]
)

print( "Stock Symbol is " , TradingSymbol )

self.get_history_data( TradingSymbol )

def get_history_data( self , TradingSymbol ) :
try :

"""Call Yahoo Finance Function () to get data """
self.df_history_data = yf.download( TradingSymbol , start = "2022-01-01" , end = "2023-10-01"
).reset_index( )
# self.df_history_data = data.DataReader( TradingSymbol , start = "2023-01-01" , end = "2023-10-01" )

# self.df_history_data = self.df_history_data.reset_index()
""" date coloumn is itself index"""

""" Convert Date to DateTime """
self.df_history_data[ Quote.mDate ] = pd.to_datetime( self.df_history_data[ Quote.mDate ] )

_count_rows_in_df = len( self.df_history_data )
print( "Row(s) present in Fetching(s) Financial Data : " , _count_rows_in_df )

self.Strat_Analysing( )
except :
print( "Error(s) Occur while Downloading.." )

Using the Correct Symbol:

Ensuring the use of the correct symbol, such as ā€œ^NSEI,ā€ for fetching historical data from the Nifty 50 index on the National Stock Exchange. This symbol is recognized by Yahoo Finance.

import Analysis_Index as IA

if __name__ == '__main__' :
My_analysis_stocks = "^NSEI"
Aq = IA.Analysis_Index( My_analysis_stocks )

Code Walkthrough:

  • Initializing the class with the stock symbol.
  • Creating a storage structure using pandas DataFrame.
  • Fetching historical financial data using Yahoo Finance.
  • Converting data to DateTime format for precise analysis (If You donā€™t wanā€™t Date column as index).
  • Handling errors gracefully for a smooth user experience.

šŸ“ŠYou can also read my other Post Like:BackTesting Strategy Setup: Building a Python Trading Strategy Analyzer

šŸ“ŠExplore the full potential of this project by visiting our GitHub repository.

Subscribe for more updates on Python tips, financial analysis, and coding adventures. Thanks for reading! For more insights on the world of finance and data-driven trading, connect with me on my LinkedIn profile.

LinkedIn : https://www.linkedin.com/in/kamalchanchal

Letā€™s stay connected and continue the conversation.šŸ“ŠšŸ’¼ #LinkedIn #Algotrading

#YahooFinance #PythonProgramming #DataAnalysis #Finance #ObjectOrientedProgramming #StockMarket #CodeExploration #LinkedInPost #MediumPost #algotrading #stockmarket #trading #python #stocksanalysis #trading

--

--

kamal chanchal

C# | Python | Capital Market | Looking for new opportunity in Trading Domain