Skip to content
Advertisement

How do I extract the last trading day from a csv file?

I have a csv file which contains 30 years of stocks data. A portion of it looks like this:

Stocks

How can I extract the last trading date of a specific month of a specific stock, say the last trading month of June 2018 of stock s_0003?

This is my code, but it doesn’t seem to be working for me because my output was 6/9/18. Is there something wrong with my code? Or is there another method I could use to extract the last trading date?

    df = pd.read_csv(stocks)

    new = df[['date', 's_0003']]
    jun = new[pd.to_datetime(new['date']).dt.month == 6]
    jun = jun[pd.to_datetime(jun['date']).dt.year == 2018]
    lastday = (max(jun['date']))

    stock0003 = df.loc[df["date"].isin([lastday]), "s_0003"]

Advertisement

Answer

Try by replacing the last 2 lines with these:

lastday = (max(pd.to_datetime(jun['date']).dt.day))

stock0003 = jun.loc[pd.to_datetime(jun['date']).dt.day == lastday, "s_0003"].iloc[0]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement