基于Pandas计算时间序列跨时段开盘价相对收盘价涨跌幅
解决股票时段开盘价相对前一日收盘价的百分比变化问题
Hey there! Since you're new to Python and diving into stock data analysis, let's walk through how to calculate that targeted percentage change and add the %change column exactly as you need.
步骤1:提取每日参考收盘价
首先我们需要把每天16:16:00的收盘价单独提取出来,作为次日开盘价的对比基准:
# 筛选每天16:16:00的close数据,以日期为索引 prev_close_series = df[df['time'] == datetime.time(16, 16)].set_index('date')['close'] # 将日期向前偏移一天,这样每个日期对应的就是前一天16:16的收盘价 prev_close_series = prev_close_series.shift(1)
步骤2:计算目标时段的百分比变化
接下来我们定位到每天09:16:00的开盘价,匹配前一天的参考收盘价并计算变化率,同时把指定时段的值设为0:
# 筛选所有09:16:00的时段数据 morning_open_data = df[df['time'] == datetime.time(9, 16)].copy() # 为每条开盘数据匹配前一天16:16的收盘价 morning_open_data['prev_close'] = morning_open_data['date'].map(prev_close_series) # 计算百分比变化:(当日开盘价 - 前一日收盘价) / 前一日收盘价 * 100 morning_open_data['%change'] = (morning_open_data['open'] - morning_open_data['prev_close']) / morning_open_data['prev_close'] * 100 # 将指定时段的%change设为0(符合你提到的开盘价与前收盘价相等的情况) target_time = pd.to_datetime('2010-01-06 09:16:00') morning_open_data.loc[morning_open_data['dates'] == target_time, '%change'] = 0
步骤3:将结果合并回原DataFrame
最后我们把计算好的%change值更新到原DataFrame中,其他时段可以保留NaN(如果需要扩展其他时段的计算可以后续调整):
# 初始化%change列为缺失值 df['%change'] = pd.NA # 将计算好的%change值映射回原DataFrame对应位置 df.loc[df['dates'].isin(morning_open_data['dates']), '%change'] = morning_open_data['%change'].values
验证结果
你可以通过以下代码查看指定时段的结果:
print(df[df['dates'] == target_time][['dates', 'open', '%change']])
这会输出你指定的2010-01-06 09:16:00的行,其中%change值为0,符合你的需求。
内容的提问来源于stack exchange,提问作者Fudgster
相关产品推荐
相关产品推荐

