如何用循环批量标注股票K线图中的水平支撑/阻力线数值
批量标注支撑/阻力位价格的正确循环实现
核心思路
直接遍历排序后的价格列表test,为每个价格值对应添加水平线(若未提前添加)和标注,确保每个标注的y坐标严格匹配当前价格,同时将标注放在K线图右侧边缘避免遮挡。
代码实现
方式1:添加水平线的同时完成标注
import mplfinance as mpf import pandas as pd # 假设已准备好股票数据df,以及排序后的支撑/阻力价格列表test fig, axlist = mpf.plot(df, type='candle', returnfig=True, figsize=(12, 8)) # 获取x轴最大坐标,用于定位标注位置 x_max = axlist[0].get_xlim()[1] for price in test: # 添加水平线 axlist[0].axhline(y=price, color='red', linestyle='--', linewidth=1) # 添加价格标注:右侧偏移5个像素,避免遮挡K线 axlist[0].annotate(f'{price:.2f}', xy=(x_max, price), xytext=(5, 0), textcoords='offset points', color='red', fontsize=9) # 调整x轴范围,防止标注被截断 axlist[0].set_xlim(axlist[0].get_xlim()[0], x_max + 0.5) mpf.show()
方式2:提前用hlines参数添加水平线,仅循环标注
如果已经通过hlines参数批量添加了水平线,只需单独处理标注:
fig, axlist = mpf.plot(df, type='candle', hlines=dict(hlines=test, colors='red', linestyle='--'), returnfig=True, figsize=(12, 8)) x_max = axlist[0].get_xlim()[1] for price in test: axlist[0].annotate(f'{price:.2f}', xy=(x_max, price), xytext=(5, 0), textcoords='offset points', color='red', fontsize=9) axlist[0].set_xlim(axlist[0].get_xlim()[0], x_max + 0.5) mpf.show()
常见问题规避
- 索引越界:直接遍历
test列表元素而非索引,避免因列表长度计算错误导致的越界。 - 标注集中在同一条线:确保
annotate的xy参数中,y值严格取当前循环的price,而非固定值。
内容的提问来源于stack exchange,提问作者astroandreas
相关产品推荐
相关产品推荐

