Support and Resistance Levels
Support is a price level where a stock tends to stop falling. At this level, demand may increase, causing the price to bounce back up.
Resistance is a price level where a stock tends to stop rising. At this level, selling pressure may increase, causing the price to pull back.
Traders often buy near support and sell near resistance to maximize profit.
Live Chart (Nifty 50 - Last 6 Months)
Click the play ▶ button in the box below to fetch the data and plot the chart:
Installing Required Python Packages
The following code uses micropip, a lightweight package installer, to install essential Python libraries like pandas and matplotlib in the browser environment. These libraries are necessary for handling stock data and visualizing support and resistance levels. Since PyScript runs Python directly in your browser using WebAssembly, external packages must be installed this way before they can be used.
import micropip import asyncio asyncio.ensure_future(micropip.install(['pandas','matplotlib','scipy','numpy']))
Fetch Stock Data
To begin the analysis, we fetch real-time stock data from Yahoo Finance using a public API endpoint that returns data in JSON format. This endpoint provides detailed stock chart data including timestamps and various price indicators such as open, high, low, and close prices. After retrieving the JSON response, we parse it to extract the relevant fields.
from pyodide.http import open_url import pandas as pd import json # Define dynamic parameters symbol = "%5ENSEI" # You can replace with other indices like ^NSEBANK, etc. interval = "1d" # Options: 1m, 2m, 5m, 15m, 1d, etc. range = "6mo" # Options: 1d, 5d, 1mo, 6mo, 1y, etc. # Construct the dynamic URL url = f"/fetch?url=https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?interval={interval}%26range={range}" # Step 2: Fetch and parse data response = open_url(url) data = response.read() parsed = json.loads(data) # Step 3: Extract time and price data chart = parsed['chart']['result'][0] timestamps = chart['timestamp'] quote = chart['indicators']['quote'][0] df = pd.DataFrame({ 'timestamp': timestamps, 'close': quote['close'], 'open': quote['open'], 'low': quote['low'], 'high': quote['high'], 'volume': quote['volume'] }) # Step 4: Convert timestamp df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s') # Drop missing values df.dropna(inplace=True) df
Identifying Support and Resistance Using Local Minima and Maxima
This code detects support and resistance levels by finding local minima and maxima in the stock price data. A sliding window of 5 days is used to check whether a price point is lower (for support) or higher (for resistance) than its surrounding values. These points are then added to the DataFrame as new columns called support and resistance. Finally, the code filters out rows that do not contain any levels and displays the most recent data points with identified support or resistance levels.
# Find support and resistance using local minima and maxima import numpy as np from scipy.signal import argrelextrema window = 5 # Change window size as needed # Find local minima (support) and maxima (resistance) df['support'] = df['low'][argrelextrema(df['low'].values, np.less_equal, order=window)[0]] df['resistance'] = df['high'][argrelextrema(df['high'].values, np.greater_equal, order=window)[0]] # Drop rows without support/resistance df_levels = df[['timestamp', 'close', 'support', 'resistance']].dropna(how='all') df_levels.tail(10) # Show last few rows with identified levels
Visualizing Support and Resistance Levels with Matplotlib
This section uses Matplotlib to plot the stock’s closing price along with the detected support and resistance levels. The main line chart shows the stock’s close prices over time, while green upward-pointing markers indicate support points (where price tends to bounce up), and red downward-pointing markers represent resistance points (where price tends to fall back). This visual representation helps traders and analysts easily identify key price zones where trend reversals are likely to occur.
import matplotlib.pyplot as plt # Plot plt.figure(figsize=(10, 6)) plt.plot(df['timestamp'], df['close'], label='Close Price', color='blue') # Plot support and resistance points plt.scatter(df['timestamp'], df['support'], label='Support', marker='^', color='green') plt.scatter(df['timestamp'], df['resistance'], label='Resistance', marker='v', color='red') plt.title('Support and Resistance Levels') plt.xlabel('Date') plt.ylabel('Price') plt.legend() plt