Python/Streamlit app for exploring Indian equities with Zerodha Kite data, generating RSI-based signals, and running a simple historical backtest.
- Authenticates with Zerodha Kite using
KITE_API_KEY,KITE_API_SECRET, andKITE_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, orHOLDfrom the latest candles - Runs a basic backtest over a selected date range
- Includes optional helpers for Discord and email alerts
You can try out the live, deployed application here: https://rsi-bot.streamlit.app/
- 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
.envfile 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.
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.
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
BUYsignal. - 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.
- 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
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
BUYsignals if the current stock price is above the 200-Day SMA. This ensures you are trading in the direction of the long-term uptrend.
- How it's used: If this filter is enabled, the bot will only consider
-
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
BUYsignal is only valid if the MACD line is above its signal line, confirming that the upward momentum is strengthening.
- How it's used: With this filter on, a
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.
When you click the "Run Backtest" button, the application performs the following steps:
- Fetches Historical Data: It retrieves the historical price data for the selected stock over your chosen date range.
- 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.
- 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
BUYsignal. - 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
SELLsignal (RSI moving above the sell threshold).
- Records Results: Every completed trade (entry date, exit date, entry price, exit price, and return percentage) is recorded in a table.
- 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.
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
Follow these steps to get the application running on your local machine.
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/activateOn Windows:
python -m venv venv
.\venv\Scripts\activateYour terminal prompt should now show (venv) at the beginning.
With your virtual environment active, install the required libraries from the requirements.txt file:
pip install -r requirements.txtCreate .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.
You have two supported flows.
Run:
python generate_token.pyIt prints a Kite login URL, asks for the full redirect URL after login, extracts request_token, and prints the new access token.
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.
streamlit run streamlit_app.pyYour web browser should automatically open with the dashboard running.
The dashboard currently supports these chart intervals:
Daily60 Minute15 Minute5 MinuteMinute
Hereβs a step-by-step walkthrough of how to use the interactive dashboard.
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.
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.
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.
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.
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.
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.
This project is for education and experimentation. It is not investment advice, and live trading based on this code is your responsibility.