Skip to content

Latest commit

Β 

History

14 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

RSI + Multi-Indicator Trading Dashboard

Python/Streamlit app for exploring Indian equities with Zerodha Kite data, generating RSI-based signals, and running a simple historical backtest.

What the code currently does

  • Authenticates with Zerodha Kite using KITE_API_KEY, KITE_API_SECRET, and KITE_ACCESS_TOKEN
  • Lists NSE and BSE equity symbols in the dashboard
  • Pulls historical OHLCV data for daily and intraday intervals
  • Computes RSI, EMA, 200-day SMA, ADX, MACD, and MACD signal
  • Generates BUY, SELL, or HOLD from the latest candles
  • Runs a basic backtest over a selected date range
  • Includes optional helpers for Discord and email alerts

πŸš€ Live Demo

You can try out the live, deployed application here: https://rsi-bot.streamlit.app/

πŸ”‘ Key Features

  • Multi-Exchange Support: Seamlessly search for and analyze stocks from both the National Stock Exchange (NSE) and Bombay Stock Exchange (BSE).
  • Flexible Strategy Logic: The core strategy is built on RSI levels and EMA crossovers. You can enhance its precision by enabling optional filters for:
    • 200-Day SMA: To confirm long-term trends.
    • ADX Strength: To ensure the market is trending and avoid sideways movement.
    • MACD Confirmation: To validate momentum before entering a trade.
  • Interactive Dashboard: A powerful Streamlit interface allows you to select stocks, tune all indicator parameters, and visualize data in real-time.
  • In-Depth Stock Analysis: View detailed price charts, key performance vitals (like today's range and 52-week highs/lows), and technical indicator graphs all in one place.
  • Comprehensive Backtesting: An integrated backtest engine simulates your strategy on historical data. It provides crucial performance metrics like Win Rate, Average Return per Trade, Total Return, and an equity curve to visualize your strategy's profitability over time.
  • Secure Configuration: Uses a .env file for local development and is compatible with Streamlit Secrets for deployment, ensuring your API keys and sensitive information are kept safe.
  • Automated Alerting: Includes modules to send trading signals and alerts via Discord or Email, helping you stay on top of market opportunities.

🧠 Understanding the Trading Strategy

This bot's logic is based on combining several well-known technical indicators to generate BUY and SELL signals. Here’s a breakdown of each component and its role in the strategy.

Core Indicators

The primary entry signal is generated by a combination of the Relative Strength Index (RSI) and other optional indicators.

  • RSI (Relative Strength Index): This is a momentum oscillator that measures the speed and change of price movements.
    • How it's used: The bot looks for "oversold" conditions. When the RSI dips below a certain threshold (e.g., 30 or 40), it suggests the stock might be undervalued and due for a rebound. This is the first condition for a potential BUY signal.
    • RSI Sell Threshold: Conversely, if the RSI goes above a high threshold (e.g., 70), it indicates an "overbought" condition, signaling a good time to exit a position.

Optional Filters for Higher Accuracy

To reduce false signals and improve the quality of trades, you can enable these optional filters. A BUY signal will only be generated if the core RSI conditions are met AND all active filters are also true.

  • 200-Day SMA (Simple Moving Average): This is the average closing price over the last 200 days, acting as a key indicator for the long-term market trend.

    • How it's used: If this filter is enabled, the bot will only consider BUY signals if the current stock price is above the 200-Day SMA. This ensures you are trading in the direction of the long-term uptrend.
  • ADX (Average Directional Index): The ADX measures the strength of a trend, regardless of its direction. It ranges from 0 to 100.

    • How it's used: When this filter is active, the bot requires the ADX value to be above a certain threshold (e.g., 20 or 25). This confirms that the market is in a strong trend and not moving sideways, which is where many strategies fail.
  • MACD (Moving Average Convergence Divergence): This indicator shows the relationship between two moving averages of a security’s price. The MACD triggers signals when it crosses above (bullish) or below (bearish) its signal line.

    • How it's used: With this filter on, a BUY signal is only valid if the MACD line is above its signal line, confirming that the upward momentum is strengthening.

πŸ§ͺ The Backtesting Engine Explained

Backtesting is the single most important feature of this application. It allows you to simulate how your strategy would have performed on historical market data, providing insights into its potential profitability and risk.

What is it doing?

When you click the "Run Backtest" button, the application performs the following steps:

  1. Fetches Historical Data: It retrieves the historical price data for the selected stock over your chosen date range.
  2. Applies Indicators: It calculates all the technical indicators (RSI, EMA, SMA, etc.) for every single day in the historical dataset based on your sidebar parameters.
  3. Simulates Trades: The engine iterates through the data, day by day, and checks if the conditions for your strategy (including all active filters) are met to generate a BUY signal.
  4. Manages Positions: Once a trade is "entered," the engine tracks the profit/loss and waits for an exit condition, which can be:
    • Hitting your Take Profit percentage.
    • Hitting your Stop Loss percentage.
    • An RSI-based SELL signal (RSI moving above the sell threshold).
  5. Records Results: Every completed trade (entry date, exit date, entry price, exit price, and return percentage) is recorded in a table.

How to Interpret the Results

  • Trades Table: This shows you every single trade the simulation made. It helps you identify which market conditions your strategy performs well or poorly in.
  • Win Rate: The percentage of trades that were profitable. A high win rate is good, but it should be considered alongside the average return.
  • Avg. Return/Trade: This tells you the average profit or loss you can expect from a single trade. A consistently positive value is a sign of a potentially effective strategy.
  • Total Return: This shows the total percentage growth of your initial capital if you had followed the strategy over the entire period.
  • Equity Curve: This is a visual representation of your portfolio's growth over time. An ideal curve should be consistently trending upwards from left to right.

πŸ“‚ Project Structure

rsi_bot/
β”œβ”€β”€ streamlit_app.py     # The main interactive web dashboard
β”œβ”€β”€ backtest.py          # The backtesting engine
β”œβ”€β”€ strategy.py          # Logic for RSI, EMA, SMA, ADX, MACD
β”œβ”€β”€ utils.py             # Utilities for Kite Connect API and data handling
β”œβ”€β”€ generate_token.py    # Script to generate a Kite Connect access token
β”œβ”€β”€ alerts.py            # Modules for sending Discord and Email alerts
β”œβ”€β”€ requirements.txt     # All Python dependencies
└── .env                 # Local environment variables for API keys

πŸ“¦ Setup and Configuration

Follow these steps to get the application running on your local machine.

1. Create a Virtual Environment (Recommended)

Before installing dependencies, it's a best practice to create a virtual environment to isolate the project's packages.

On macOS / Linux:

python3 -m venv venv
source venv/bin/activate

On Windows:

python -m venv venv
.\venv\Scripts\activate

Your terminal prompt should now show (venv) at the beginning.

2. Install Dependencies

With your virtual environment active, install the required libraries from the requirements.txt file:

pip install -r requirements.txt

3. Configure environment variables

Create .env in the repo root:

KITE_API_KEY="your_api_key"
KITE_API_SECRET="your_api_secret"
KITE_ACCESS_TOKEN="your_access_token"

For Streamlit Cloud, set the same values in app secrets instead.

Generating an access token

You have two supported flows.

Option 1: Script

Run:

python generate_token.py

It prints a Kite login URL, asks for the full redirect URL after login, extracts request_token, and prints the new access token.

Option 2: In-app flow

If the configured token is missing or expired, streamlit_app.py shows a sidebar login button. After authorizing Kite, the app can read the request_token from the redirect query string and display the new access token directly in the UI.

Running the app

streamlit run streamlit_app.py

Your web browser should automatically open with the dashboard running.

πŸ“Š How to Use the Dashboard: A Visual Guide

The dashboard currently supports these chart intervals:

  • Daily
  • 60 Minute
  • 15 Minute
  • 5 Minute
  • Minute

Here’s a step-by-step walkthrough of how to use the interactive dashboard.

Step 1: Select a Stock

Begin by typing the name or symbol of a stock into the search box (Preferred in Upper Case). The application will fetch matching symbols from both the NSE and BSE for you to choose from.

Step 2: Analyze the Price Chart and Vitals

Once a stock is selected, the dashboard displays its historical price chart and a detailed "Performance & Price Vitals" section, showing today's range, 52-week highs/lows, volume, and circuit limits.

Step 3: Configure Your Strategy

Use the sidebar on the left to fine-tune your trading strategy. You can adjust the periods for the RSI, set your buy/sell thresholds, and enable or disable the SMA, ADX, and MACD filters to see how they affect the current signal.

Step 4: Check the Live Signal and Indicator Charts

Based on your settings, the app will show you the current signal ('BUY', 'SELL', or 'HOLD'). You can expand the "Detailed Indicator Charts" to see the RSI, EMA, ADX, and MACD indicators plotted, giving you a complete technical overview.

Step 5: Run a Backtest

Scroll down to the "Backtest Your Strategy" section. Set your desired date range, define your Stop Loss and Take Profit percentages, and click the "Run Backtest on Historical Data" button to simulate your strategy.

Step 6: Evaluate Performance

The results of the backtest will be displayed in a table listing every simulated trade. Below the table, you'll find key performance metrics (Win Rate, Average Return, Total Return) and an equity curve chart that visualizes the growth of your initial capital over time.

⚠️ Disclaimer

This project is for education and experimentation. It is not investment advice, and live trading based on this code is your responsibility.

About

An interactive stock backtesting tool & trading bot using Python & Streamlit. Implements an RSI-based strategy with EMA, SMA, ADX & MACD filters for Indian stocks (NSE/BSE).

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages