Py学习  »  Python

使用Python计算支撑位和阻力位:详细教程

QuantML • 1 月前 • 149 次点击  

引言

在技术分析中,支撑位阻力位是帮助交易者识别价格趋势可能反转的关键价格水平。

理解这些关键价格水平,就像是掌握了股市的“地图”,能帮你找到最佳的买卖时机。不管你是短线交易员,还是长线投资者,掌握支撑位和阻力位都能让你的投资决策更明智。

本文将详细介绍如何使用Python计算和可视化这些关键价格水平。我们将使用yahooquerypandasscipy mplfinance等库来实现这一目标。


1. 安装必要的库

首先,确保你已经安装了以下Python库:

pip install yahooquery pandas scipy mplfinance
  • yahooquery: 用于从Yahoo Finance获取股票数据。
  • pandas: 用于数据处理和分析。
  • scipy: 用于信号处理,特别是峰值检测。
  • mplfinance: 用于绘制金融图表。

2. 导入库并加载数据

import yahooquery as yq
import pandas as pd
import scipy as sp
import mplfinance as mpf
import numpy as np

接下来,我们使用yahooquery加载Apple公司的历史每日价格数据:

# 初始化Ticker对象
ticker = yq.Ticker('AAPL')

# 获取历史每日价格数据
df = ticker.history(period='max', interval= '1d')

# 查看数据
print(df.head())

注意df将包含以下列:openhighlowclosevolume adjclose。我们主要关注highlow列来识别支撑位和阻力位。

3. 可视化历史价格数据

在识别支撑位和阻力位之前,先可视化历史价格数据以获得更好的上下文。

# 将索引转换为日期时间格式
df.index = pd.to_datetime(df.index)

# 绘制蜡烛图
mpf.plot(df, type='candle', style='charles', title='AAPL Candlestick Chart', volume=True)
AAPL Candlestick Chart

4. 使用SciPy识别峰值和谷值

4.1 识别强峰值(阻力位)

我们将使用scipy.signal.find_peaks函数来检测局部最大值(峰值),这些峰值可以作为潜在的阻力位。

from scipy.signal import find_peaks

# 定义强峰值的距离(天数)
strong_peak_distance = 60# 例如,60天

# 定义强峰值的显著性(prominence)
strong_peak_prominence = 20# 显著性阈值

# 找到'高'价格数据中的强峰值
strong_peaks, _ = find_peaks(df['high'], distance=strong_peak_distance, prominence=strong_peak_prominence)

# 提取强峰值的对应高值
strong_peaks_values = df.iloc[strong_peaks]['high'].tolist()

# 包括52周最高价作为额外的强峰值
yearly_high = df['high'].iloc[-252:].max()
strong_peaks_values.append(yearly_high)

print("强峰值(阻力位):", strong_peaks_values)

4.2 识别强谷值(支撑位)

类似地,我们可以识别强谷值(支撑位):

# 找到'低'价格数据中的强谷值
strong_troughs, _ = find_peaks(-df['low'], distance=strong_peak_distance, prominence=strong_peak_prominence)

# 提取强谷值的对应低值
strong_troughs_values = df.iloc[strong_troughs]['low'].tolist()

# 包括52周最低价作为额外的强谷值
yearly_low = df['low'].iloc[-252:].min()
strong_troughs_values.append(yearly_low)

print("强谷值(支撑位):", strong_troughs_values)

5. 计算强支撑位和阻力位

5.1 强阻力位

# 创建一个列表,包含水平线以绘制为阻力位
add_plot_resistance = [mpf.make_addplot(np.full(len(df), resistance), color='r', linestyle='--'for resistance in strong_peaks_values]

# 绘制包含强阻力位的蜡烛图
mpf.plot(df, type='candle', style='charles', title='AAPL Candlestick Chart with Strong Resistance Lines', volume=True, addplot=add_plot_resistance)
AAPL Candlestick Chart with Strong Resistance Lines

5.2 强支撑位

# 创建一个列表包含水平线以绘制为支撑位
add_plot_support = [mpf.make_addplot(np.full(len(df), support), color='g', linestyle='--'for support in strong_troughs_values]

# 绘制包含强支撑位的蜡烛图
mpf.plot(df, type='candle', style='charles', title='AAPL Candlestick Chart with Strong Support Lines', volume=True, add_plot=add_plot_support)

6. 计算一般支撑位和阻力位

6.1 一般阻力位

一般峰值(一般阻力位)具有较弱的显著性(prominence)和较短的间距(distance)。我们使用以下步骤:

# 定义一般峰值之间的距离(天数)
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)
AAPL Candlestick Chart with Support and Resistance Levels

通过本文,我们详细介绍了如何使用Python计算和可视化支撑位和阻力位。我们使用了yahooquery获取数据,scipy进行峰值检测,mplfinance进行可视化。通过这种方法,我们可以识别出对交易决策至关重要的关键价格水平。






完整代码见星球,加入QuantML星球,与750+专业人士一起交流学习:


往期回顾

       QuantML-Qlib开发版:



Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/179660
 
149 次点击