You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何绘制上下影线与K线实体同粗的蜡烛图?

自定义粗细影线的蜡烛图实现(Matplotlib)

直接用Matplotlib原生API可以实现影线与实体同宽的蜡烛图,以下是完整实现步骤:

1. 导入依赖并获取数据

首先用yfinance获取标准OHLC数据:

import yfinance as yf
import matplotlib.pyplot as plt

# 下载示例数据(以AAPL为例)
df = yf.download('AAPL', start='2024-01-01', end='2024-02-01')
# 重置索引方便后续处理(也可直接用iloc操作)
df.reset_index(inplace=True)

2. 设置核心参数

定义K线的整体宽度(实体与影线共用该宽度):

bar_width = 0.6  # K线宽度,可按需调整
colors = {'up': '#00ff00', 'down': '#ff0000'}  # 涨跌颜色自定义

3. 遍历绘制每个K线

循环处理每一行数据,分别绘制实体、上影线、下影线:

plt.figure(figsize=(12, 6))

for i in range(len(df)):
    open_price = df.iloc[i]['Open']
    close_price = df.iloc[i]['Close']
    high_price = df.iloc[i]['High']
    low_price = df.iloc[i]['Low']
    
    # 确定涨跌颜色
    color = colors['up'] if close_price >= open_price else colors['down']
    
    # 绘制K线实体
    plt.bar(
        x=i,
        height=abs(close_price - open_price),
        width=bar_width,
        bottom=min(open_price, close_price),
        color=color
    )
    
    # 绘制上影线:同宽度矩形连接实体顶部与最高价
    if high_price > max(open_price, close_price):
        plt.bar(
            x=i,
            height=high_price - max(open_price, close_price),
            width=bar_width,
            bottom=max(open_price, close_price),
            color=color
        )
    
    # 绘制下影线:同宽度矩形连接最低价与实体底部
    if low_price < min(open_price, close_price):
        plt.bar(
            x=i,
            height=min(open_price, close_price) - low_price,
            width=bar_width,
            bottom=low_price,
            color=color
        )

# 设置x轴刻度为日期
plt.xticks(
    ticks=range(len(df)),
    labels=df['Date'].dt.strftime('%Y-%m-%d'),
    rotation=45,
    ha='right'
)

plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Custom Candlestick Chart (Same Width for Body & Wicks)')
plt.tight_layout()  # 自动调整布局避免标签截断
plt.show()

关键说明

  • 没有用plt.vlines画影线,而是用plt.bar绘制同宽度矩形,确保影线粗细和实体完全一致。
  • 涨跌颜色、K线宽度可根据需求自行修改,也可添加边框等额外样式。
  • 若需保留原始datetime索引,可不执行reset_index,循环时直接通过range(len(df))遍历即可。

内容的提问来源于stack exchange,提问作者Quim Quadrada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 15:15:38