benito.cano
benito.cano

Reputation: 837

How to index out the past month in pandas?

Okay so I was wondering if it was possible to index out 4 months in pandas, without specifiying the exact months. So say the code was:

import pandas as pd
import datetime as dt
import pandas_datareader as web

start_date = '2019-01-01'
end_date = '2020-11-01'

df = web.datareader('AMD', yahoo, start, end)

This code is pulling almost 2 years of data, so my questions is how can index out the last 4 months, without specifying july 1, 2020 to now? (The reason for this by the way is that say that I always needed the past 4 months, well as time progress the july, 1, 2020 will no longer be the last 4 months so I was trying to find a way that would find the last 4 months without having to change it every day)

Upvotes: 0

Views: 231

Answers (2)

BhishanPoudel
BhishanPoudel

Reputation: 17144

You can use date and relativedelta from datetime module.

import pandas as pd
import pandas_datareader as web
from datetime import date
from dateutil.relativedelta import relativedelta

end = date.today()
start = end + relativedelta(months=-4)
stocks = ['AMD']

df = web.DataReader(stocks, 'yahoo', start, end)

Output

print(df.head(2).append(df.tail(2)))
Attributes  Adj Close      Close       High        Low       Open    Volume
Symbols           AMD        AMD        AMD        AMD        AMD       AMD
Date                                                                       
2020-08-11  76.879997  76.879997  80.709999  76.099998  80.709999  77877700
2020-08-12  82.610001  82.610001  82.879997  77.550003  78.430000  88607800
2020-12-10  91.660004  91.660004  92.089996  89.029999  89.550003  33771700
2020-12-11  90.440002  90.440002  91.790001  90.160004  89.550003   3404191

Upvotes: 1

C.Georgiadis
C.Georgiadis

Reputation: 219

you can define start_date and end_date dynamically, for example:

from datetime import date
from dateutil.relativedelta import relativedelta

end_date = date.today().strftime("%Y-%m-%d")

start_date = (date.today() - relativedelta(months=4)).strftime("%Y-%m-%d")

Upvotes: 1

Related Questions