Как использовать технический индикатор ADX (Average Directional Index) в торговых стратегиях

Пожалуйста, наслаждайтесь этим основным разрушением технического индикатора ADX.

import pandas as pd

def calculate_adx(prices, n=14):
  # Calculate the difference between high and low prices
  diff = prices['high'] - prices['low']

  # Calculate the difference between the current high and the previous high
  up_move = prices['high'] - prices['high'].shift(1)

  # Calculate the difference between the current low and the previous low
  down_move = prices['low'].shift(1) - prices['low']

  # Calculate the positive and negative directional movement
  plus_dm = up_move.where(up_move > down_move, 0)
  minus_dm = down_move.where(down_move > up_move, 0)

  # Calculate the average directional movement over the specified number of periods
  truerange = prices['high'] - prices['low']
  plus_dm_avg = plus_dm.rolling(n).mean()
  minus_dm_avg = minus_dm.rolling(n).mean()
  truerange_avg = truerange.rolling(n).mean()

  # Calculate the average directional index
  adx = 100 * (plus_dm_avg / truerange_avg) / (plus_dm_avg / truerange_avg + minus_dm_avg / truerange_avg)

  return adx

# Load the stock prices
prices = pd.read_csv('stock_prices.csv')

# Calculate the ADX
adx = calculate_adx(prices)

# Use the ADX to make trading decisions
if adx > 25:
  # ADX is high, indicating a strong trend
  if adx > 50:
    # ADX is very high, indicating a very strong trend
    # Consider buying if the trend is up or selling if the trend is down
    if adx.shift(1) < adx:
      # Trend is up, consider buying
      print("Buy")
    else:
      # Trend is down, consider selling
      print("Sell")
  else:
    # ADX is high but not very high, indicating a moderate trend
    # Consider buying or selling based on other factors
    print("Moderate trend, consider other factors before making a decision")
else:
  # ADX is low, indicating a weak trend or no trend
  # Consider other factors before making a decision
  print("Weak trend, consider other factors before making a decision")

Этот код сначала вычисляет ADX с помощью функции calculate_adx(). Затем он использует значение ADX для принятия торговых решений на основе силы тренда. Если ADX высокий (больше 25), это указывает на сильный тренд.

  • Если ADX очень высок (больше 50), это указывает на очень сильный тренд. В любом из этих случаев код рассматривает покупку, если тренд восходящий, или продажу, если тренд нисходящий.
  • Если ADX умеренный (между 25 и 50), код учитывает другие факторы, прежде чем принимать решение.
  • Если ADX низкий (менее 25), это указывает на слабый тренд или его отсутствие, и код снова учитывает другие факторы.