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

如何在Matplotlib绘制的股票K线图中连接蜡烛低点绘制趋势线?

如何在Matplotlib蜡烛图上添加低点趋势线?

我来帮你实现这个需求!要在你现有的SPY蜡烛图上添加连接指定低点的趋势线,只需要在原有代码基础上增加几行Matplotlib的绘图逻辑即可。下面是修改后的完整代码,我会逐步说明关键部分:

#import modules
import pandas as pd
from matplotlib.finance import candlestick2_ohlc
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt

#build the dataframe
api = 'http://finance.google.com/finance/getprices?q=SPY&i=300&p=3d&f=d,o,h,l,c,'
df = pd.read_csv(api, skiprows=8, header=None)
df.columns = ['Record', 'Open', 'High', 'Low', 'Close']

#build candlestick chart
quotes = df[-36:]
fig, ax = plt.subplots()
candlestick2_ohlc(ax,quotes['Open'],quotes['High'],quotes['Low'],quotes['Close'],width=0.6)
ax.xaxis.set_major_locator(ticker.MaxNLocator(6))
fig.autofmt_xdate()
fig.tight_layout()
plt.xlabel('5 Min Chart')

# --- 新增趋势线绘制代码 ---
# 定义要连接的两个低点:当前最后一根蜡烛 & 10根之前的蜡烛
# 获取两个点的x轴位置(蜡烛图x轴为0开始的连续索引)
x_left = len(quotes) - 11  # 往前数10根的位置(索引从0开始,所以减11)
x_right = len(quotes) - 1  # 当前最后一根蜡烛的位置
# 获取对应位置的低点数值
y_left = quotes['Low'].iloc[-11]
y_right = quotes['Low'].iloc[-1]

# 绘制趋势线,可自定义样式
ax.plot([x_left, x_right], [y_left, y_right], 
        color='#ff4444', linestyle='--', linewidth=2, 
        label='Low Trend Line (10-period)')
ax.legend(loc='upper right')  # 显示图例,指定位置

plt.savefig('candle.jpg')

关键部分说明:

  • x轴位置定位:candlestick2_ohlc绘制的蜡烛图,x轴是从0开始的连续整数,每一个整数对应一根蜡烛的位置。所以我们通过len(quotes)-11定位到10根之前的蜡烛(因为索引从0开始,最后一根是len(quotes)-1,往前数10根就是减11)。
  • 趋势线样式自定义:你可以调整color(颜色)、linestyle(线型,比如实线-、虚线--)、linewidth(线宽)来匹配你的需求,添加图例能让图表更直观。
  • 灵活调整点位:如果需要连接其他位置的低点,只需要修改x_left、y_left对应的索引即可(比如改成20根之前的低点,就把-11换成-21)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:43:53