12

I have a Yahoo finance daily stock price imported in a pandas dataframe. I want to use .resample() to convert it to the monthly stock price by taking the price of the first QUOTED daily price of each month.

.resample('MS', how='first')

returns the correct price of each month but it changes the index to the first day of the month while in general the first day of a month for a quoted price maybe 2nd or 3rd of the month because of holidays and weekends.

How can I use resample() by only resampling the existing dates and not changing them?

Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
Amin
  • 1,883
  • 4
  • 17
  • 22

1 Answers1

18

I think what you want is BMS (business month start):

.resample('BMS').first()

Note: Prior to pandas 0.18 this was done using the deprecated how kwarg:

.resample('BMS', how='first')

An alternative would be to groupby month and take the first with a plain ol' groupby (and e.g. use nth to get the first entry in each group):

.groupby(pd.Grouper(freq='M')).nth(0)

Note: Prior to pandas 0.21 this was done using the deprecated TimeGrouper:

.groupby(pd.TimeGrouper('M')).nth(0)
fantabolous
  • 21,470
  • 7
  • 54
  • 51
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • the groupby solution was what I was looking for, but it is still sort of strange to me that resample, doesnt really sample from the existing dates (like what we did in groupby). Thanks a lot Andy – Amin Apr 26 '15 at 15:18
  • 1
    @Andy Hayden This does not appear to work in the latest version of pandas. Any thoughts on how to achieve this now? – derNincompoop Dec 20 '17 at 15:42
  • @derNincompoop the API is now `s.resample('BMS').first()` – Andy Hayden Dec 20 '17 at 19:39