Devesh Agrawal
Devesh Agrawal

Reputation: 9212

converting daily stock data to weekly in pandas in Python

I have following data format.

Date          Open      High        Low     Close
2018-11-12  **10607.80**  10645.50  10464.05  10482.20
2018-11-13  10451.90  10596.25  10440.55  10582.50
2018-11-14  10634.90  10651.60  10532.70  10576.30
2018-11-15  10580.60  10646.50  10557.50  10616.70
2018-11-16  10644.00  10695.15  10631.15  **10682.20**
2018-11-19  **10731.25**  10774.70  10688.80  10763.40
2018-11-20  10740.10  10740.85  10640.85  10656.20
2018-11-21  10670.95  10671.30  10562.35  10600.05
2018-11-22  10612.65  10646.25  10512.00  **10526.75**
2018-11-26  **10568.30**  10637.80  10489.75  10628.60
2018-11-27  10621.45  10695.15  10596.35  10685.60
2018-11-28  10708.75  10757.80  10699.85  10728.85
2018-11-29  10808.70  10883.05  10782.35  10858.70
2018-11-30  10892.10  10922.45  10835.10  **10876.75**

I want to get the open price of monday and closing price of following Friday.

This is my code for same.

open = df.Open.resample('W-MON').last()
print open.tail(5)

close = df.Close.resample('W-FRI').last().resample('W-MON').first()
print close.tail(5)

weekly_data = pd.concat([open, close], axis=1)

print weekly_data.tail(5)

It gives me correct data for open and close individually, but when i merge to weekly_data, it gives wrong output for close. It shows me previous friday closing price.

How to fix this issue?

Upvotes: 3

Views: 1789

Answers (1)

jezrael
jezrael

Reputation: 863611

You can use shift by -4 days for align both DatetimeIndex:

open = df.Open.resample('W-MON').last()
print (open.tail(5))
Date
2018-11-12    10607.80
2018-11-19    10731.25
2018-11-26    10568.30
2018-12-03    10892.10
Freq: W-MON, Name: Open, dtype: float64

close = df.Close.resample('W-FRI').last().shift(-4, freq='D')
print (close.tail(5))
Date
2018-11-12    10682.20
2018-11-19    10526.75
2018-11-26    10876.75
Freq: W-MON, Name: Close, dtype: float64

weekly_data = pd.concat([open, close], axis=1)
print (weekly_data)
                Open     Close
Date                          
2018-11-12  10607.80  10682.20
2018-11-19  10731.25  10526.75
2018-11-26  10568.30  10876.75
2018-12-03  10892.10       NaN

Upvotes: 3

Related Questions