0

I have a Panda series of closing price of a stock, display as below:

closingprice[date1]

date1

> 1/3/2017  151.732605 
  1/9/2017  152.910522 
  1/27/2017 153.945938
> 2/23/2017 167.495438 
  3/6/2017  158.808716 
  3/9/2017  157.894333
> 3/10/2017 157.513321 
  3/13/2017 156.7323 
  3/21/2017 158.856354
> 3/24/2017 158.132462 
  4/3/2017  158.780151 
  4/12/2017 162.085281

I need to look for what is the closing price for 30 days later, e.g, I have 2017-01-03 and I would need to have 2017-02-02 closing price. So I did:

date2 = date1 + pd.DateOffset(days=30) i have the new Service which shows below:

closingprice[date2]

> 2/2/2017  159.731018 
  2/8/2017  160.418427 
  2/26/2017 NaN 
  3/25/2017 NaN
> 4/5/2017  159.065903 
  4/8/2017  NaN 
  4/9/2017  NaN

As you can see, some date which are not located on business date and given me as NaN. If that's the case, how can I get the next business date price if the 30 days located on a weekend or holiday? e.g: Feb 26th nan need to replace to Feb 27th closing price.

Chelseajcole
  • 487
  • 1
  • 9
  • 16

1 Answers1

0

One trick is to add 30 days to each date, and then to add zero BusinessDays to each date.

from pandas.tseries.offsets import BDay
date2 = date1 + pd.DateOffset(days=30)  # some of these dates may fall on weekends
date3 = date2 + 0*BDay()  # this nudges any weekend dates to the next occurring Monday

This doesn't affect weekdays, but it transforms weekend dates to the next occurring Monday. (Note that "business day" in this case only refers to Monday–Friday, with no provision for holidays of any kind.)

Source: @phil_20686's answer to this question: Pandas offset DatetimeIndex to next business if date is not a business day

Peter Leimbigler
  • 10,775
  • 1
  • 23
  • 37