Build a Stock Tracker with Python: India Guide

Learn to build a Python stock tracker from scratch. This India-focused guide uses free tools & NSE data to teach data fetching, analysis, and visualization—a perfect project for your tech portfolio.

LB
UnboxCareer Team
Editorial · Free courses curator
February 10, 20265 min read
Build a Stock Tracker with Python: India Guide

For any B.Tech student in India today, the gap between textbook theory and real-world application can feel massive. You've learned Python basics, but how do you use it to solve a tangible, high-value problem? Building a stock tracker is the perfect project. It bridges finance and technology, two of India's hottest career fields, and gives you a practical skill that recruiters at companies like Zerodha, Paytm Money, and Angel One actively seek. This isn't just about plotting lines on a chart; it's about automating data analysis, a core skill for roles in fintech, data science, and quantitative analysis.

Why Build a Python Stock Tracker?

In India's booming fintech and IT services sector, demonstrating applied Python skills can set you apart. A stock tracker project showcases your ability to work with real-time data, APIs, and data visualization—competencies directly relevant to employers like TCS, Infosys, HCL, and startups like Razorpay and Smallcase.

  • Skill Demonstration: It proves you can handle pandas for data manipulation, matplotlib or Plotly for visualization, and API integration.
  • Financial Literacy: It forces you to understand key metrics like moving averages, volume, and returns, which are discussed in interviews for finance-adjacent tech roles.
  • Portfolio Project: A completed tracker is a concrete item for your GitHub and resume, far more impressive than a list of course certificates. It can help you target positions with salaries ranging from ₹6-12 LPA for freshers in analytics or backend development.

Prerequisites & Tools You'll Need

You don't need to be a Python expert. A solid grasp of fundamentals—variables, loops, functions, and lists—is enough to start. We'll use free libraries and data sources.

  1. Python 3.7+: Ensure it's installed. Use python --version in your terminal to check.
  2. Code Editor: VS Code or PyCharm Community Edition are excellent free choices.
  3. Key Python Libraries: Install these using pip install in your terminal.
    • pandas: The backbone for data analysis and manipulation.
    • yfinance: A brilliant, free library to fetch historical and real-time stock data from Yahoo Finance (includes Indian stocks).
    • matplotlib or plotly: For creating static or interactive charts.
  4. Basic Finance Concepts: Understand what a stock's Open, High, Low, Close (OHLC) price and Volume mean.

Step-by-Step: Building Your Basic Tracker

Let's build a tracker that fetches data for Indian stocks and creates a simple closing price chart.

1. Setting Up and Fetching Data

First, import the necessary libraries and use yfinance to get data. It uses ticker symbols. For NSE stocks, append .NS. For example, Reliance Industries is RELIANCE.NS, and TCS is TCS.NS.

import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt

# Define the stock ticker and period
ticker_symbol = "RELIANCE.NS"
start_date = "2023-01-01"
end_date = "2024-01-01"

# Download historical data
stock_data = yf.download(ticker_symbol, start=start_date, end=end_date)

# Display the first few rows
print(stock_data.head())

The stock_data variable is a pandas DataFrame containing OHLC prices, volume, and adjusted close prices.

2. Calculating Basic Metrics

Real trackers analyze data, not just store it. Let's add a simple moving average, a common indicator.

# Calculate 50-day Simple Moving Average (SMA)
stock_data['SMA_50'] = stock_data['Close'].rolling(window=50).mean()

# Calculate daily percentage return
stock_data['Daily_Return'] = stock_data['Close'].pct_change() * 100

# Display the new columns
print(stock_data[['Close', 'SMA_50', 'Daily_Return']].tail())

3. Visualizing the Data

A chart makes trends clear. We'll plot the closing price and its 50-day moving average.

plt.figure(figsize=(14, 7))
plt.plot(stock_data.index, stock_data['Close'], label='Closing Price', alpha=0.7)
plt.plot(stock_data.index, stock_data['SMA_50'], label='50-Day SMA', linestyle='--')
plt.title(f'{ticker_symbol} Stock Price and Moving Average')
plt.xlabel('Date')
plt.ylabel('Price (₹)')
plt.legend()
plt.grid(True)
plt.show()

You now have a functional, basic stock tracker! The next step is to enhance it.

Taking Your Tracker to the Next Level

A basic script is good; a robust application is great. Here’s how to level up.

Add Multiple Stocks & Comparison

Track a portfolio by fetching data for multiple tickers and comparing their performance.

tickers = ["TCS.NS", "INFY.NS", "WIPRO.NS", "HCLTECH.NS"]
portfolio_data = yf.download(tickers, start=start_date, end=end_date)['Close']
# Normalize to compare performance from a common starting point
normalized_data = (portfolio_data / portfolio_data.iloc[0]) * 100
normalized_data.plot(figsize=(14,7))
plt.title('IT Sector Stocks - Normalized Performance')
plt.ylabel('Normalized Price (Base=100)')
plt.show()

Incorporate Fundamental Data

Use yfinance's Ticker module to pull key metrics like P/E ratio, which is crucial for value investing.

reliance = yf.Ticker("RELIANCE.NS")
# Get key financial info
pe_ratio = reliance.info['trailingPE']
market_cap = reliance.info['marketCap']
print(f"P/E Ratio: {pe_ratio}")
print(f"Market Cap: ₹{market_cap:,.0f}")

Build a Simple Alert System

Simulate price alerts by checking if the current price crosses a threshold. (For true real-time alerts, you would need a scheduler like schedule library).

current_price = stock_data['Close'].iloc[-1]
alert_price = 2800  # Set your alert threshold

if current_price > alert_price:
    print(f"Alert: {ticker_symbol} is above ₹{alert_price}. Current: ₹{current_price:.2f}")

Common Challenges & How to Solve Them

You will hit roadblocks. Here are solutions to typical issues Indian students face.

  • "Data fetching is slow or fails." yfinance is reliable but rate-limited. Add pauses using time.sleep() if fetching many stocks. For more robust data, explore free APIs from NSE India or BSE, though they may have steeper learning curves.
  • "My charts look messy." Start simple. Use plt.tight_layout() to adjust spacing. For interactive, web-ready charts, learn Plotly, which is highly valued in analytics dashboards.
  • "How do I handle corporate actions?" Always use the 'Adj Close' column provided by yfinance for analysis. It accounts for splits and dividends, giving you the true return.
  • "I want to add more complex indicators." Explore the ta (Technical Analysis) library. Install it (pip install ta) to easily calculate RSI, MACD, Bollinger Bands, and more with a single line of code.

From Project to Portfolio: Showcasing Your Work

Building it is half the battle. Presenting it professionally completes the loop.

  1. Clean Your Code: Add comments, use functions for different tasks (e.g., fetch_data(), calculate_metrics(), plot_chart()), and ensure it's readable.
  2. Host on GitHub: Create a repository. Include a detailed README.md file explaining the project, its features, installation steps (requirements.txt), and a screenshot of the output.
  3. Write a LinkedIn Post: Share what you learned—the technical challenges (API integration, pandas operations) and the finance concepts. Tag it with #Python #Fintech #DataAnalysis. This public build-in-progress is noticed by recruiters.
  4. Link in Your Resume: Under a "Projects" section, describe the tracker, the tech stack used, and the value it provides (e.g., "Built a Python-based stock analysis tool fetching live NSE data to visualize trends and calculate key financial indicators").

Next Steps

Your first stock tracker is a launchpad. To dive deeper into the intersection of Python and finance, explore our curated list of free finance and data science courses from platforms like NPTEL and Coursera. If you need to strengthen your core Python skills first, browse our Python programming guides featuring tutorials from CodeWithHarry and Apna College. Ready to see what others have built? Check out more advanced project ideas to inspire your next creation.

Keep learning on UnboxCareer

Explore free courses, certificates, and career roadmaps curated for Indian students.