Skip to main content

Download [work] Bhavcopy From Nse Using Python For Loop -

import requests import pandas as pd from datetime import datetime, timedelta import os # 1. Define the date range start_date = datetime(2024, 1, 1) end_date = datetime(2024, 1, 10) date_list = pd.date_range(start_date, end_date) # 2. Set headers to emulate a real browser (required by NSE) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } # 3. Create a for loop to iterate through each date for current_date in date_list: # Format date to match NSE naming convention (DDMMYYYY) date_str = current_date.strftime('%d%m%Y') # Construct the URL url = f"https://nsearchives.nseindia.com/products/content/sec_bhavdata_full_{date_str}.csv" file_name = f"bhavcopy_{date_str}.csv" try: response = requests.get(url, headers=headers) # Check if the market was open (returns 200) or closed (returns 404) if response.status_code == 200: with open(file_name, 'wb') as f: f.write(response.content) print(f"Successfully downloaded: {file_name}") else: print(f"No data for {date_str} (Market likely closed)") except Exception as e: print(f"Error downloading {date_str}: {e}") Use code with caution. Key Considerations

: NSE does not generate Bhavcopy files for Saturdays, Sundays, or trading holidays. Your loop should include a check for the status_code (e.g., 200 vs. 404) to avoid saving empty files. download bhavcopy from nse using python for loop

: Direct requests without a User-Agent header are often blocked by NSE's security. import requests import pandas as pd from datetime

Alternatively , older archives may use: https://www.nseindia.com/content/historical/EQUITIES/{YEAR}/{MONTH}/cm{DD}{MONTH}{YEAR}bhav.csv.zip Python Script: Downloading with a For Loop Create a for loop to iterate through each