Categories
Uncategorized

A generic way to detect support and resistance with Python

Detecting support and resistance levels in financial data involves analyzing historical price movements to identify levels at which the price has historically had difficulty moving below (support) or above (resistance). Here’s a basic example of how you can use Python and a popular library like pandas to detect support and resistance levels:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import argrelextrema

# Load historical price data (you can get this data from a financial API or a CSV file)
# For the sake of example, let's create a simple price dataset
data = {
    'Date': pd.date_range(start='2023-01-01', end='2023-12-31'),
    'Close': [100, 110, 95, 120, 90, 115, 105, 125, 85, 130, 110, 140]
}

df = pd.DataFrame(data)
df.set_index('Date', inplace=True)

# Smooth the data using a moving average to identify significant peaks and troughs
window_size = 3
df['SMA'] = df['Close'].rolling(window=window_size).mean()

# Identify local minima (support levels) and maxima (resistance levels)
minima_idx = argrelextrema(df['SMA'].values, np.less, order=window_size)[0]
maxima_idx = argrelextrema(df['SMA'].values, np.greater, order=window_size)[0]

support_levels = df.iloc[minima_idx]['Close']
resistance_levels = df.iloc[maxima_idx]['Close']

# Plotting
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Close'], label='Close Price')
plt.plot(df.index, df['SMA'], label=f'SMA ({window_size} periods)')
plt.scatter(support_levels.index, support_levels.values, color='green', label='Support Levels', marker='^')
plt.scatter(resistance_levels.index, resistance_levels.values, color='red', label='Resistance Levels', marker='v')
plt.title('Support and Resistance Levels Detection')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()

In this example:

  • We use a simple moving average (SMA) to smooth the price data.
  • We identify local minima and maxima in the smoothed data using argrelextrema from scipy.signal.
  • The identified minima correspond to potential support levels, and the identified maxima correspond to potential resistance levels.
  • We plot the original closing prices along with the smoothed curve and mark the detected support and resistance levels.

This is a basic example, and in a real-world scenario, you might want to use more sophisticated techniques and additional indicators to improve the accuracy of support and resistance level detection. Additionally, you could explore libraries like ta-lib for technical analysis or machine learning models for more advanced pattern recognition.

Leave a Reply

Your email address will not be published. Required fields are marked *