• Products
    Investment Suite
    Stocks
    Mutual Funds
    Future and Options
    IPO
    Exchange Traded Funds
    Commodity
    Stockcase (Stock Baskets)
    Non Convertible Debentures
    Sovereign Gold Bond
    Exclusive
    NRI Account
    Corporate/HUF Trading Account
    Private Client Group
    Features
    SipIt
    MTF
    Investment Suite
    Exclusive
    Features
    Stocks
    Mutual Funds
    Future and Options
    IPO
    Exchange Traded Funds
    Commodity
    Stockcase (Stock Baskets)
    Non Convertible Debentures
    Sovereign Gold Bond
    NRI Account
    Corporate/HUF Trading Account
    Private Client Group
    SipIt
    MTF
  • Platform
    Trading Platforms
    Kotak Neo App & Web
    Nest Trading Terminal
    NEO Trade APIs
    Trade From Charts
    Features and Tools
    MTF
    Securities Accepted as Collateral
    Margin Requirements
    Equity Screeners
    Payoff Analyzer
    Calculators
    SIP Calculator
    Lumpsum Calculator
    Brokerage Calculator
    Margin Calculator
    MTF Calculator
    SWP Calculator
    CAGR Calculator
    Simple Interest Calculator
    ELSS Calculator
    Step up SIP Calculator
    All Calculators
    Trading Platforms
    Features and Tools
    Calculators
    Kotak Neo App & Web
    Nest Trading Terminal
    NEO Trade APIs
    Trade From Charts
    MTF
    Securities Accepted as Collateral
    Margin Requirements
    Equity Screeners
    Payoff Analyzer
    SIP Calculator
    Lumpsum Calculator
    Brokerage Calculator
    Margin Calculator
    MTF Calculator
    SWP Calculator
    CAGR Calculator
    Simple Interest Calculator
    ELSS Calculator
    Step up SIP Calculator
  • Pricing
  • Research
    Research Calls
    Long Term calls
    Short Term calls
    Intraday calls
    Derivatives calls
    Pick of the week
    Top Monthly Picks
    Stock Research Recommendations
    MTF Stock Recommendations
    Research Reports
    Fundamental Research Report
    Technical Research Report
    Derivative Research Report
    Commodities Research Report
    Research Calls
    Research Reports
    Long Term calls
    Short Term calls
    Intraday calls
    Derivatives calls
    Pick of the week
    Top Monthly Picks
    Stock Research Recommendations
    MTF Stock Recommendations
    Fundamental Research Report
    Technical Research Report
    Derivative Research Report
    Commodities Research Report
  • Market
    Market Movers
    Share Market Today
    Top Gainers
    Top Losers
    Stocks
    Large Cap
    Mid Cap
    Small Cap
    Indices
    Nifty 50
    Nifty Bank
    FinNifty
    Nifty Midcap India
    India VIX
    All Indices
    Mutual Funds
    SBI Mutual Funds
    HDFC Mutual Funds
    Axis Mutual Funds
    ICICI Prudential Mutual Funds
    Nippon India Mutual Funds
    All AMC's
    IPO
    Upcoming IPO
    Current IPO
    IPO Allotment Status
    IPO Subscription Status
    Closed IPO
    Recently Listed IPO
    Quarterly Results
    Australian Premium Solar (India)'s Q2 FY 2025-26 Quarterly Results
    SG Mart's Q2 FY 2025-26 Quarterly Results
    Rajoo Engineers' Q2 FY 2025-26 Quarterly Results
    Hybrid Financial Services' Q2 FY 2025-26 Quarterly Results
    Market Movers
    Stocks
    Indices
    Mutual Funds
    IPO
    Quarterly Results
    Share Market Today
    Top Gainers
    Top Losers
    52 Week High
    52 Week Low
    Volume Shockers
    Large Cap
    Mid Cap
    Small Cap
    State Bank of India
    Reliance Industries Ltd
    HDFC Bank Ltd
    Infosys Ltd
    Tata Capital
    LG Electronics India
    Tata Consultancy Services Ltd
    Hindustan Unilever Ltd
    ITC Ltd
    IRCTC
    NSE
    Nifty 50
    Nifty Bank
    FinNifty
    Nifty Midcap India
    India VIX
    BSE
    Sensex
    BSE Bankex
    BSE Small Cap
    BSE Mid Cap
    BSE 100
    Global Indices
    Gift Nifty
    Dow Jones
    Nikkei Index
    Hong Kong Index
    KOSPI Index
    AMC's
    SBI Mutual Funds
    HDFC Mutual Funds
    Axis Mutual Funds
    ICICI Prudential Mutual Funds
    Nippon India Mutual Funds
    Schemes
    Parag Parikh Flexi Cap
    SBI Small Cap Fund
    SBI Contra Fund
    Nippon Small Cap Fund
    ICICI Pru Technology Fund
    NFO
    Upcoming IPO
    Current IPO
    IPO Allotment Status
    IPO Subscription Status
    Closed IPO
    Recently Listed IPO
    Safecure Services IPO
    Orkla India IPO
    Studds IPO
    Lenskart IPO
    Curis Lifesciences IPO
    Finbud Financial Services IPO
    Shreeji Global FMCG IPO
    Groww IPO
    Australian Premium Solar (India)'s Q2 FY 2025-26 Quarterly Results
    SG Mart's Q2 FY 2025-26 Quarterly Results
    Rajoo Engineers' Q2 FY 2025-26 Quarterly Results
    Hybrid Financial Services' Q2 FY 2025-26 Quarterly Results
    Inventurus Knowledge Solutions' Q2 FY 2025-26 Quarterly Results
    Onelife Capital Advisors' Q2 FY 2025-26 Quarterly Results
    Jet Freight Logistics' Q2 FY 2025-26 Quarterly Results
    Xchanging Solutions' Q2 FY 2025-26 Quarterly Results
    Welspun Corp's Q2 FY 2025-26 Quarterly Results
    United Spirits' Q2 FY 2025-26 Quarterly Results
    Union Bank of India's Q2 FY 2025-26 Quarterly Results
    TD Power Systems' Q2 FY 2025-26 Quarterly Results
  • Learn
    Stockshaala
    Basics of Stock Market
    Introduction to Fundamental Analysis
    Introduction to Technical Analysis
    Derivatives, Risk management & Option Trading Strategies
    Personal Finance
    Explore More
    Resource
    Market Ready
    Kotak Insights
    Infographic
    Podcast
    Webinars
    Youtube Channel
    Investing Guide
    Demat Account
    Trading Account
    Share Market
    Intraday Trading
    IPO
    Mutual Funds
    Events
    Budget 2025
    Muhurat Trading
    Share Market Holiday
    Market Outlook 2025
    Stockshaala
    Resource
    Investing Guide
    Events
    Basics of Stock Market
    Introduction to Fundamental Analysis
    Introduction to Technical Analysis
    Derivatives, Risk management & Option Trading Strategies
    Personal Finance
    Market Ready
    Kotak Insights
    Infographic
    Podcast
    Webinars
    Youtube Channel
    Demat Account
    Trading Account
    Share Market
    Intraday Trading
    IPO
    Mutual Funds
    Budget 2025
    Muhurat Trading
    Share Market Holiday
    Market Outlook 2025
  • Partner
    Business Associates
    Kotak Connect Plus
    Startup connect
    Business Associates
    Kotak Connect Plus
    Startup connect
  • Support
    FAQs
    Circulars
    Bulletins
    Contact Us
    Forms Download
    Get your Statement
    FAQs
    Circulars
    Bulletins
    Contact Us
    Forms Download
    Get your Statement
  • News

logo
Algorithmic Trading
6 Modules | 23 Chapters
Module 4
Coding and Deploying Algos
Course Index

A Sample Algo Trading Strategy in Python

Let’s build a simple intraday strategy:
Buy when RSI < 30 and Close > 20 EMA
Sell when RSI > 70 and Close < 20 EMA

We’ll use:

  • yfinance for data
  • ta for indicators
  • Python logic for strategy

This is for learning/demo only. Not for live trading — yet!

1. Install necessary libraries (only once): You can run this in Google Colab or your local Python setup.

!pip install yfinance ta

Note:

This command installs two Python libraries needed for market data analysis and technical indicator calculations:

  • yfinance – used to fetch historical and real-time market data directly from Yahoo Finance into Python.

  • ta – a Technical Analysis library that provides ready-to-use functions for computing indicators like RSI, EMA, MACD, Bollinger Bands, etc.

The ! at the start allows this to be run as a shell command inside Jupyter Notebook or Google Colab, so the packages are installed into your current environment before running the rest of your algo trading code.

2. Import the libraries

import yfinance as yf import ta import pandas as pd

Note:

This code imports three essential Python libraries for algo trading:

  • yfinance (yf) to fetch historical and real-time market data from Yahoo Finance.

  • ta to calculate technical indicators such as RSI, EMA, MACD, Bollinger Bands, and others.

  • pandas (pd) for storing, processing, and analyzing time-series market data in DataFrames.

Together, they allow you to download price data, calculate technical indicators, and manipulate the resulting dataset for strategy building and backtesting.

3. Get intraday price data

data = yf.download("RELIANCE.NS", period="5d", interval="15m") data.dropna(inplace=True)

This gives you 15-minute candles of Reliance for the last 5 days. The securities quoted are exemplary and are not recommendatory

4. Calculate RSI and 20 EMA

data['rsi'] = ta.momentum.RSIIndicator(close=data['Close']).rsi() data['ema20'] = ta.trend.EMAIndicator(close=data['Close'], window=20).ema_indicator()

Note:

  1. ta.momentum.RSIIndicator: Creates a Relative Strength Index (RSI) indicator object from the ta (technical analysis) library.

  2. close=data['Close']: Uses the 'Close' price column from your data DataFrame to calculate RSI.

  3. .rsi(): Computes the RSI values for each row (default period is usually 14 unless specified) and returns a Pandas Series.

  4. data['rsi'] = ...: Stores the resulting RSI values in a new column called 'rsi' in your DataFrame.

  5. ta.trend.EMAIndicator: Creates an Exponential Moving Average (EMA) indicator object.

  6. close=data['Close']: Again, uses the 'Close' price as the data source for calculation.

  7. window=20: Sets the EMA lookback period to 20 bars (e.g., 20 days for daily data).

  8. .ema_indicator(): Calculates the EMA values for the given period.

  9. data['ema20'] = ...: Saves the computed EMA values into a new column 'ema20' in your DataFrame.

Boom — indicators added to your DataFrame.

5. Define the Buy/Sell logic

def generate_signal(row): if row['rsi'] < 30 and row['Close'] > row['ema20']: return "BUY" elif row['rsi'] > 70 and row['Close'] < row['ema20']: return "SELL" else: return "HOLD"

data['signal'] = data.apply(generate_signal, axis=1)

This function checks every row (i.e., every 15-min candle) and assigns a signal

6. View the result

print(data[['Close', 'rsi', 'ema20', 'signal']].tail(10))

Note:

This line prints the last 10 rows of selected columns from the data DataFrame:

  • 'Close' – the closing price of the asset for each period.

  • 'rsi' – the Relative Strength Index values calculated earlier.

  • 'ema20' – the 20-period Exponential Moving Average values.

  • 'signal' – a trading signal column (likely generated by your strategy logic).

The .tail(10) function limits the output to the most recent 10 rows, making it easier to review the latest market data, indicators, and generated trade signals without printing the entire dataset.

You’ll see output like:

Close RSI EMA20 Signal
2850
29
2830
BUY
2895
72
2901
HOLD
2880
74
2885
SELL

This helps you backtest if the logic makes sense visually.

  • Pulled real data
  • Calculated indicators
  • Checked for buy/sell signals
  • Gave you a ready “signal” column

You can now add order execution, logging, and alerts to this strategy step by step.

Want to see how many buy/sell signals came up?

print(data['signal'].value_counts())

Is this chapter helpful?
Share
What could we have done to make this article better?

Tools for Coded Algo Trading
Deploying Your Algo for Live Trading

Disclaimer: This article is for informational purposes only and does not constitute financial advice. It is not produced by the desk of the Kotak Securities Research Team, nor is it a report published by the Kotak Securities Research Team. The information presented is compiled from several secondary sources available on the internet and may change over time. Investors should conduct their own research and consult with financial professionals before making any investment decisions. Read the full disclaimer here.

Investments in securities market are subject to market risks, read all the related documents carefully before investing. Brokerage will not exceed SEBI prescribed limit. The securities are quoted as an example and not as a recommendation. SEBI Registration No-INZ000200137 Member Id NSE-08081; BSE-673; MSE-1024, MCX-56285, NCDEX-1262.

Tools for Coded Algo Trading
Deploying Your Algo for Live Trading

Disclaimer: This article is for informational purposes only and does not constitute financial advice. It is not produced by the desk of the Kotak Securities Research Team, nor is it a report published by the Kotak Securities Research Team. The information presented is compiled from several secondary sources available on the internet and may change over time. Investors should conduct their own research and consult with financial professionals before making any investment decisions. Read the full disclaimer here.

Investments in securities market are subject to market risks, read all the related documents carefully before investing. Brokerage will not exceed SEBI prescribed limit. The securities are quoted as an example and not as a recommendation. SEBI Registration No-INZ000200137 Member Id NSE-08081; BSE-673; MSE-1024, MCX-56285, NCDEX-1262.

Beyond Stockshaala

Discover our extensive knowledge center

Kotak Insights

An insightful weekend read on market trends, company stories, and historical events.

Neo Shorts

A visual spotlight on buzzing sectors and rising stars of the Indian stock market.

Investing Guide

Comprehensive library of blogs focussed to build your financial confidence.

Market Ready

Stay ahead of the game with daily market trends, global insights, and key investment updates.

Webinars

Live sessions with industry leaders for in-depth market knowledge.

Podcast

Latest trends, strategies, and market updates with our seasoned experts.