如何计算交易日累计多/空K线总数并实现按日开盘时段动态累加统计与绘图
计算交易日多空K线累计数量及动态可视化解决方案
一、计算交易日内累计的多头/空头K线总数
首先得明确**多头K线(bull candle)和空头K线(bear candle)**的定义:通常收盘价 > 开盘价为多头,收盘价 < 开盘价为空头;若收盘价=开盘价,可标记为中性(这里我们暂时忽略不计入多空统计)。
假设你用Python的pandas处理行情数据,步骤如下:
1. 数据预处理与K线类型标记
先加载数据并给每根K线打上类型标签:
import pandas as pd import numpy as np # 加载你的行情数据(示例:包含datetime、open、close列) df = pd.read_csv('market_data.csv', parse_dates=['datetime'], index_col='datetime') # 标记K线类型:1=多头,-1=空头,0=中性 df['candle_type'] = np.where( df['close'] > df['open'], 1, np.where(df['close'] < df['open'], -1, 0) )
2. 按交易日分组统计总数
通过groupby按日期聚合,统计每个交易日的多空K线总数:
# 按交易日分组,计算当日累计多头、空头数量 daily_candle_counts = df.groupby(df.index.date).agg( total_bull_candles=('candle_type', lambda x: (x == 1).sum()), total_bear_candles=('candle_type', lambda x: (x == -1).sum()) ) # 查看结果 print(daily_candle_counts.head())
这段代码会输出每个交易日的多头、空头K线总数,示例结果如下:
total_bull_candles total_bear_candles 2024-01-02 35 29 2024-01-03 41 23 ...
二、动态累加统计多空K线并绘图展示
要实现从开盘起动态累加统计,我们需要对每个交易日内的K线按时间顺序计算累计值,再可视化这个变化过程。
1. 计算交易日内的动态累计值
对每个交易日单独计算累计多头/空头数量,用cumsum实现动态累加:
# 确保数据按时间升序排列(避免乱序导致累计错误) df = df.sort_index() # 按交易日分组,计算截至当前K线的累计多头/空头数量 df['cumulative_bull'] = df.groupby(df.index.date)['candle_type'].apply( lambda x: (x == 1).cumsum() ) df['cumulative_bear'] = df.groupby(df.index.date)['candle_type'].apply( lambda x: (x == -1).cumsum() )
2. 可视化动态累计趋势
用matplotlib绘制单交易日的累计变化曲线(也可以用plotly做交互式图):
import matplotlib.pyplot as plt # 选择要展示的目标交易日(示例:取第一个交易日) target_date = df.index.date[0] single_day_data = df[df.index.date == target_date] # 绘图 plt.figure(figsize=(12, 6)) plt.plot(single_day_data.index, single_day_data['cumulative_bull'], color='green', linewidth=2, label='累计多头K线') plt.plot(single_day_data.index, single_day_data['cumulative_bear'], color='red', linewidth=2, label='累计空头K线') plt.title(f'{target_date} 交易日多空K线累计数量变化', fontsize=14) plt.xlabel('交易时间', fontsize=12) plt.ylabel('累计数量', fontsize=12) plt.legend(fontsize=12) plt.grid(alpha=0.3) plt.xticks(rotation=45) plt.tight_layout() plt.show()
运行后会生成一张直观的趋势图:绿色线随时间逐步上升代表累计多头K线数量,红色线代表累计空头K线数量,能清晰展示当日多空力量的变化节奏。如果需要批量展示多个交易日的情况,可以用循环生成子图,或者用seaborn做分组可视化。
内容的提问来源于stack exchange,提问作者Blind Blake




