# 定义一般峰值之间的距离(天数) peak_distance = 5 # 定义峰值合并的宽度(垂直距离) peak_rank_width = 2 # 定义支撑位最小反转次数 resistance_min_pivot_rank = 3 # 找到'高'价格数据中的峰值 peaks, _ = find_peaks(df['high'], distance=peak_distance) # 初始化字典以跟踪每个峰值的排名 peak_to_rank = {peak: 0for peak in peaks} # 遍历所有一般峰值,比较它们的接近程度并排名 for i, current_peak in enumerate(peaks): current_high = df.iloc[current_peak]['high'] for previous_peak in peaks[:i]: if abs(current_high - df.iloc[previous_peak]['high']) <= peak_rank_width: peak_to_rank[current_peak] += 1 # 初始化包含强峰值的阻力位列表 resistances = strong_peaks_values.copy() # 遍历每个一般峰值,如果其排名达到阈值,则添加到阻力位列表 for peak, rank in peak_to_rank.items(): if rank >= resistance_min_pivot_rank: resistances.append(df.iloc[peak]['high'] + 1e-3) # 添加小量以避免浮点精度问题 # 对阻力位进行排序 resistances.sort() # 合并接近的阻力位 resistance_bins = [] current_bin = [resistances[0]] for r in resistances[1:]: if r - current_bin[-1] < peak_rank_width: current_bin.append(r) else: resistance_bins.append(current_bin) current_bin = [r] resistance_bins.append(current_bin) # 计算每个阻力位区间的平均值 final_resistances = [np.mean(bin) for bin in resistance_bins] print("一般阻力位:", final_resistances)
6.2 一般支撑位
类似地,我们可以计算一般支撑位:
# 找到'低'价格数据中的谷值 troughs, _ = find_peaks(-df['low'], distance=peak_distance) # 初始化字典以跟踪每个谷值的排名 trough_to_rank = {trough: 0for trough in troughs} # 遍历所有一般谷值,比较它们的接近程度并排名 for i, current_trough in enumerate(troughs): current_low = df.iloc[current_trough]['low'] for previous_trough in troughs[:i]: if abs(current_low - df.iloc[previous_trough]['low']) <= peak_rank_width: trough_to_rank[current_trough] += 1 # 初始化包含强谷值的支撑位列表 supports = strong_troughs_values.copy() # 遍历每个一般谷值,如果其排名达到阈值,则添加到支撑位列表 for trough, rank in trough_to_rank.items(): if rank >= resistance_min_pivot_rank: supports.append(df.iloc[trough]['low'] - 1e-3) # 添加小量以避免浮点精度问题 # 对支撑位进行排序 supports.sort() # 合并接近的支撑位 support_bins = [] current_bin = [supports[0]] for s in supports[1:]: if s - current_bin[-1] < peak_rank_width: current_bin.append(s) else: support_bins.append(current_bin) current_bin = [s]
support_bins.append(current_bin) # 计算每个支撑位区间的平均值 final_supports = [np.mean(bin) for bin in support_bins] print("一般支撑位:", final_supports)
7. 合并接近的支撑位和阻力位
为了使图表更清晰,我们可以合并接近的支撑位和阻力位:
# 合并接近的阻力位 merged_resistances = [] for bin in resistance_bins: merged_resistances.append(np.mean(bin)) # 合并接近的支撑位 merged_supports = [] for bin in support_bins: merged_supports.append(np.mean(bin)) print("合并后的阻力位:", merged_resistances) print("合并后的支撑位:", merged_supports)
8. 可视化支撑位和阻力位
# 创建包含阻力位的添加图 add_plot_resistance = [mpf.make_addplot(np.full(len(df), resistance), color='r', linestyle='--') for resistance in merged_resistances] # 创建包含支撑位的添加图 add_plot_support = [mpf.make_addplot(np.full(len(df), support), color='g', linestyle='--') for support in merged_supports] # 绘制包含支撑位和阻力位的蜡烛图 mpf.plot(df, type='candle', style='charles', title='AAPL Candlestick Chart with Support and Resistance Levels', volume=True, addplot=add_plot_resistance + add_plot_support)