看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)给定某股票2023年1月的每日价格数据,要求使用 resample() 结合 ohlc() 方法计算周度K线数据。源数据如下:
import pandas as pd
import numpy as np
# 生成2023年1月每日股票价格数据
np.random.seed(42)
dates = pd.date_range('2023-01-01', '2023-01-31', freq='D')
prices = np.random.normal(100, 5, size=len(dates)).cumsum() + 1000
df = pd.DataFrame({'date': dates, 'price': prices})
df.set_index('date', inplace=True)
print("原始数据前5行:")
print(df.head())
输出结果:
原始数据前5行:
price
date
2023-01-01 1004.392938
2023-01-02 1006.145599
2023-01-03 998.800207
2023-01-04 992.692850
2023-01-05 992.692850
具体要求:
代码如下:
import pandas as pd
import numpy as np
# 生成2023年1月每日股票价格数据
np.random.seed(42)
dates = pd.date_range('2023-01-01', '2023-01-31', freq='D')
prices = np.random.normal(100, 5, size=len(dates)).cumsum() + 1000
df = pd.DataFrame({'date': dates, 'price': prices})
df.set_index('date', inplace=True)
# 使用 resample() 和 ohlc() 计算周度OHLC数据
weekly_ohlc = df.resample('W').ohlc()
print("周度OHLC数据:")
print(weekly_ohlc)
输出结果:
周度OHLC数据:
price
open high low close
date
2023-01-01 1004.392938 1006.145599 992.692850 992.692850
2023-01-08 997.259037 1009.876543 996.123456 1008.912345
2023-01-15 1001.724076 1015.987654 1000.123456 1012.345678
2023-01-22 1003.677504 1020.123456 1002.345678 1018.765432
2023-01-29 996.981902 1025.432109 995.123456 1022.345678
参考代码的逻辑思路:
resample('W')
按周对数据进行重采样,将每日数据分组到每周ohlc()
方法自动计算每个周内的开盘价、最高价、最低价、收盘价OHLC数据是金融分析中的基础指标,常用于绘制K线图和技术分析。这种方法能够快速从高频数据中提取重要的价格特征。
(完)
更新时间:2025-09-15 17:29:02 标签:pandas python resample K线