繁体   English   中英

用Python在pandas中将每日股票数据转换为每周一次

[英]converting daily stock data to weekly in pandas in Python

我有以下数据格式。

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**

我想得到星期一的开盘价以及下周五的收盘价。

这是我的代码。

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)

它为我提供了单独打开和关闭的正确数据,但是当我合并到weekly_data时,它会为关闭提供错误的输出。 它显示了我上周五的收盘价。

如何解决这个问题?

你可以使用shift -4天来对齐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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM