Column missing after append and concat in python pandas

Question:

Try to download historical stock prices for bunch of stock scrips and concat the file. The issue is final output does not give me the ‘Date’ column which is the first column

Here is my code:

from nsepy import get_history
import pandas as pd
from datetime import date

#Equity details contains list of stock symbols - Example: SBIN, AARTIPHARM, KFINTECH, HDFC
equity_details = pd.read_csv('C:/Users/am364971/Downloads/EQUITY_SAMPLE.csv')
equity_details.rename(columns={"SYMBOL": "Symbol"}, inplace=True)

# Create empty list df to append the output data from 'For loop' below
df = []

# So the for loop will download historical stock price details one at a time and append to the list df

for name in equity_details.Symbol:
    try:
        data = get_history(symbol=name,
                   start=date(2023,1,1),
                   end=date(2023,2,28))
        df.append(data)         
    except Exception as e:
        print(f'{name} ===> {e}')

df = pd.concat(df)

df.to_csv(f'C:/Data/Combined_StockPrices.csv')

The problem is the final output does not have the ‘Date’ column. Please guide on what I am missing

Asked By: Nithish

||

Answers:

There is no "Date" column in your df because it was set as an index. Try adding .reset_index() before concatenating:

data = get_history(symbol=name,start=date(2023,1,1),end=date(2023,2,28)).reset_index()
Answered By: dramarama