Sidebar and Body Layout

Python code to get stock price of Nifty Bank Open and Close Prices

Python code to get stock price of Nifty Bank Open and Close Prices using yfinance library. Dive into this tutorial to unlock the potential of yfinance, simplifying financial data retrieval and analysis for both seasoned quants and novice investors alike.

For a detailed explanation, check out the video here.

Description of the image

import yfinance as yf
import pandas as pd
from datetime import datetime, timedelta

def get_nifty_bank_open_prices(input_date):
    try:
        
        interval = '5m'
        duration = '1d'
        
      
        input_datetime = datetime.strptime(input_date, '%Y-%m-%d')
        
      
        nifty_bank_data = yf.download("^NSEBANK", start=input_datetime, end=input_datetime + timedelta(days=1), interval=interval)
        
        if nifty_bank_data is not None and not nifty_bank_data.empty:
          
            open_prices = nifty_bank_data.resample('5T').first()['Open']
            close_prices = nifty_bank_data.resample('5T').last()['Close']
            
         
            open_prices_rounded = open_prices.round(1)
            close_prices_rounded = close_prices.round(1)
            
           
            df = pd.DataFrame({'Datetime': open_prices.index, 
                               'Date': open_prices.index.date, 
                               'Time': open_prices.index.strftime('%H:%M'), 
                               'Open': open_prices_rounded.values,
                               'Close': close_prices_rounded.values})
            
            return df
        else:
            print("Failed to fetch Nifty Bank price data or empty data returned.")
            return None
    except Exception as e:
        print(f"Error fetching Nifty Bank data: {e}")
        return None


input_date = input("Enter the date (YYYY-MM-DD): ")


#pd.set_option('display.max_rows', None)


nifty_bank_data = get_nifty_bank_open_prices(input_date)

if nifty_bank_data is not None:
    #print(nifty_bank_data)
    output_file = 'nifty_bank_prices.csv'
    nifty_bank_data.to_csv(output_file, index=False)
    print(f"DataFrame exported to '{output_file}'")