Skip to main content

Overview

The single_stock_analyzer.py script provides detailed fundamental analysis for any stock in the ChartsMaze database. It extracts quarterly results, ratios, and ownership data directly from fundamental_data.json. Use Case: Quick inspection of a single stock’s fundamentals without processing the entire dataset.

Quick Start

1

Ensure fundamental_data.json exists

The analyzer requires fundamental_data.json from the pipeline:
cd ~/workspace/source/DO\ NOT\ DELETE\ EDL\ PIPELINE/
ls -lh fundamental_data.json
If missing, fetch it:
python3 fetch_dhan_data.py
python3 fetch_fundamental_data.py
2

Run the analyzer

python3 single_stock_analyzer.py SYMBOL
Example:
python3 single_stock_analyzer.py RELIANCE
3

Review output

The script prints comprehensive fundamental metrics to console (see Output Format below).

Usage

Basic Syntax

python3 single_stock_analyzer.py <SYMBOL>
Parameters:
  • <SYMBOL>: NSE stock symbol (e.g., RELIANCE, TCS, INFY, HDFCBANK)

Examples

# Analyze Reliance Industries
python3 single_stock_analyzer.py RELIANCE

# Analyze TCS
python3 single_stock_analyzer.py TCS

# Analyze HDFC Bank
python3 single_stock_analyzer.py HDFCBANK

# Analyze Infosys
python3 single_stock_analyzer.py INFY

Error Handling

Missing file:
python3 single_stock_analyzer.py RELIANCE
Error: fundamental_data.json not found.
Invalid symbol:
python3 single_stock_analyzer.py INVALID123
Stock 'INVALID123' not found in database.
No arguments:
python3 single_stock_analyzer.py
Usage: python3 single_stock_analyzer.py <SYMBOL>
Example: python3 single_stock_analyzer.py RELIANCE

Output Format

Sample Output (RELIANCE)

--- Analysis for RELIANCE ---

Net Profit Latest Quarter: 18200.0
Net Profit Previous Quarter: 17250.0
Net Profit 2 Quarters Back: 16800.0
Net Profit 3 Quarters Back: 16200.0
Net Profit Last Year Quarter: 16100.0
QoQ % Net Profit Latest: 5.51%
YoY % Net Profit Latest: 13.04%

EPS Latest Quarter: 27.5
EPS Previous Quarter: 26.1
EPS 2 Quarters Back: 25.4
EPS 3 Quarters Back: 24.5
EPS Last Year Quarter: 24.3
QoQ % EPS Latest: 5.36%
YoY % EPS Latest: 13.17%
EPS Last Year: 102.3
EPS 2 Years Back: 95.7

Sales Latest Quarter: 235000.0
Sales Previous Quarter: 228000.0
Sales 2 Quarters Back: 221000.0
Sales 3 Quarters Back: 218000.0
Sales Last Year Quarter: 215000.0
QoQ % Sales Latest: 3.07%
YoY % Sales Latest: 9.30%
Sales Growth 5 Years(%): 8.45%

OPM Latest Quarter: 12.5
OPM Previous Quarter: 12.1
OPM 2 Quarters Back: 11.8
OPM 3 Quarters Back: 11.5
OPM Last Year Quarter: 11.2
QoQ % OPM Latest: 3.31%
YoY % OPM Latest: 11.61%

Latest Quarter: Dec 2025
ROE(%): 15.2
ROCE(%): 18.7
D/E: 0.58
OPM TTM(%): 12.0
P/E: 28.5
FII % change QoQ: 1.25%
DII % change QoQ: -0.35%
PEG: 2.16
Forward P/E: 26.3
Historical P/E 5: 0.0 (Data Unavailable)

Metrics Explained

1. Net Profit Analysis

MetricDescription
Net Profit Latest QuarterNet profit for most recent quarter (in Crores)
Net Profit Previous QuarterNet profit for Q-1
Net Profit 2/3 Quarters BackNet profit for Q-2, Q-3
Net Profit Last Year QuarterNet profit for same quarter last year (for YoY comparison)
QoQ % Net Profit LatestQuarter-over-Quarter growth: (Latest - Previous) / Previous * 100
YoY % Net Profit LatestYear-over-Year growth: (Latest - Last Year Q) / Last Year Q * 100
Interpretation:
  • Positive QoQ: Sequential improvement
  • Positive YoY: Year-over-year growth
  • Consistent growth across quarters: Strong momentum

2. Earnings Per Share (EPS)

MetricDescription
EPS Latest QuarterEarnings per share for latest quarter (₹)
EPS Previous/2Q/3Q BackHistorical quarterly EPS
EPS Last Year QuarterSame quarter last year (for YoY)
QoQ % EPS LatestSequential EPS growth
YoY % EPS LatestYear-over-year EPS growth
EPS Last YearFull-year EPS for previous fiscal year
EPS 2 Years BackEPS from 2 years ago
Interpretation:
  • Rising EPS: Improving profitability per share
  • YoY > 15%: High growth stock
  • Compare with P/E to assess valuation

3. Sales (Revenue)

MetricDescription
Sales Latest QuarterTotal revenue for latest quarter (in Crores)
Sales Previous/2Q/3Q BackHistorical quarterly revenue
Sales Last Year QuarterSame quarter last year
QoQ % Sales LatestSequential revenue growth
YoY % Sales LatestYear-over-year revenue growth
Sales Growth 5 Years(%)5-year CAGR: ((Current / 5Y Ago)^(1/5) - 1) * 100
Interpretation:
  • Consistent sales growth: Market share expansion
  • 5Y CAGR > 10%: Strong long-term growth
  • Compare with profit growth to assess margin trends

4. Operating Profit Margin (OPM)

MetricDescription
OPM Latest QuarterOperating margin % for latest quarter
OPM Previous/2Q/3Q BackHistorical quarterly margins
OPM Last Year QuarterSame quarter last year
QoQ % OPM LatestSequential margin change
YoY % OPM LatestYear-over-year margin change
OPM TTM(%)Trailing Twelve Months operating margin
Interpretation:
  • Rising OPM: Improving operational efficiency
  • OPM > 15%: High-margin business
  • Declining OPM with rising sales: Volume growth at cost of margins

5. Valuation Ratios

MetricDescriptionFormula
P/EPrice-to-Earnings ratioStock Price / TTM EPS
Forward P/EForward Price-to-EarningsPrice / (Latest Q EPS * 4)
PEGPrice/Earnings to GrowthP/E / YoY EPS Growth %
Historical P/E 55-year average P/ENot available in current data
Interpretation:
  • P/E < 15: Potentially undervalued (or low growth)
  • P/E 15-25: Fairly valued
  • P/E > 25: Premium valuation (growth stock) or overvalued
  • Forward P/E < Current P/E: Earnings expected to grow
  • PEG < 1: Undervalued relative to growth
  • PEG > 2: Overvalued relative to growth

6. Return Ratios

MetricDescriptionBenchmark
ROE(%)Return on Equity> 15% is good
ROCE(%)Return on Capital Employed> 15% is good
D/EDebt-to-Equity ratio< 1.0 is healthy
Interpretation:
  • ROE > 15%: Efficient use of shareholder equity
  • ROCE > ROE: Efficient use of total capital
  • D/E < 0.5: Conservative leverage
  • D/E 0.5-1.0: Moderate leverage
  • D/E > 1.0: High debt (check industry norms)

7. Ownership Changes

MetricDescription
FII % change QoQForeign Institutional Investor holdings change (percentage points)
DII % change QoQDomestic Institutional Investor holdings change (percentage points)
Interpretation:
  • FII increase: Positive institutional sentiment
  • DII increase: Domestic confidence
  • Both increasing: Strong accumulation
  • Both decreasing: Institutional selling pressure

Data Source Structure

The analyzer reads from fundamental_data.json, which contains:

Data Sections

{
  "Symbol": "RELIANCE",
  "incomeStat_cq": {  // Quarterly Income Statement (Current Quarter)
    "NET_PROFIT": "18200|17250|16800|16200|16100",  // Latest|Q-1|Q-2|Q-3|Last Year Q
    "EPS": "27.5|26.1|25.4|24.5|24.3",
    "SALES": "235000|228000|221000|218000|215000",
    "OPM": "12.5|12.1|11.8|11.5|11.2",
    "YEAR": "Dec 2025|Sep 2025|Jun 2025|Mar 2025|Dec 2024"
  },
  "incomeStat_cy": {  // Annual Income Statement (Current Year)
    "EPS": "102.3|95.7|88.2|82.1|75.6",  // FY2025|FY2024|FY2023|...
    "SALES": "902000|850000|780000|720000|650000"
  },
  "TTM_cy": {  // Trailing Twelve Months
    "OPM": "12.0",
    "EPS": "105.8"
  },
  "CV": {  // Current Valuation
    "STOCK_PE": "28.5"
  },
  "roce_roe": {
    "ROE": "15.2",
    "ROCE": "18.7"
  },
  "sHp": {  // Shareholding Pattern
    "FII": "24.5|23.25",  // Latest|Previous
    "DII": "18.2|18.55"
  },
  "bs_c": {  // Balance Sheet Consolidated
    "NON_CURRENT_LIABILITIES": "185000|...",
    "TOTAL_EQUITY": "320000|..."
  }
}

Pipe-Separated Values

Most fields use pipe (|) separation for time series:
"NET_PROFIT": "18200|17250|16800|16200|16100"
                 ^      ^      ^      ^      ^
              Latest  Q-1    Q-2    Q-3   Last Year Q
Indexing:
  • index 0 = Latest quarter
  • index 1 = Previous quarter (Q-1)
  • index 2 = 2 quarters back (Q-2)
  • index 3 = 3 quarters back (Q-3)
  • index 4 = Last year same quarter (for YoY)

Use Cases

1. Pre-Investment Due Diligence

# Quick fundamental check before buying
python3 single_stock_analyzer.py TATAMOTORS
Look for:
  • Consistent QoQ and YoY growth in sales and profits
  • Improving or stable OPM
  • ROE > 15%, ROCE > 15%
  • PEG ratio < 1.5
  • Positive FII/DII changes

2. Quarterly Results Analysis

# After company announces Q4 results
python3 single_stock_analyzer.py INFY
Check:
  • Latest quarter vs previous quarter (QoQ growth)
  • Latest quarter vs last year same quarter (YoY growth)
  • Margin expansion or compression

3. Peer Comparison

# Compare IT sector stocks
python3 single_stock_analyzer.py TCS > tcs_analysis.txt
python3 single_stock_analyzer.py INFY > infy_analysis.txt
python3 single_stock_analyzer.py WIPRO > wipro_analysis.txt

# Compare key metrics manually or with diff
diff tcs_analysis.txt infy_analysis.txt

4. Tracking Portfolio Stocks

#!/bin/bash
# Daily fundamental check for portfolio

for stock in RELIANCE TCS HDFCBANK INFY ICICIBANK
do
    echo "\n=== $stock ==="
    python3 single_stock_analyzer.py $stock | grep -E "(YoY|ROE|P/E)"
done
Output:
=== RELIANCE ===
YoY % Net Profit Latest: 13.04%
YoY % EPS Latest: 13.17%
YoY % Sales Latest: 9.30%
ROE(%): 15.2
P/E: 28.5

=== TCS ===
YoY % Net Profit Latest: 8.2%
...

Scripting & Automation

Extract Specific Metrics

# Get only ROE and ROCE
python3 single_stock_analyzer.py RELIANCE | grep -E "(ROE|ROCE)"
Output:
ROE(%): 15.2
ROCE(%): 18.7

Batch Processing

#!/usr/bin/env python3
import subprocess
import re

stocks = ['RELIANCE', 'TCS', 'INFY', 'HDFCBANK', 'ICICIBANK']

for symbol in stocks:
    result = subprocess.run(
        ['python3', 'single_stock_analyzer.py', symbol],
        capture_output=True,
        text=True
    )
    
    # Extract ROE
    roe_match = re.search(r'ROE\(%\): ([0-9.]+)', result.stdout)
    roe = float(roe_match.group(1)) if roe_match else 0
    
    # Extract P/E
    pe_match = re.search(r'P/E: ([0-9.]+)', result.stdout)
    pe = float(pe_match.group(1)) if pe_match else 0
    
    print(f"{symbol:12} | ROE: {roe:5.1f}% | P/E: {pe:5.1f}")
Output:
RELIANCE     | ROE:  15.2% | P/E:  28.5
TCS          | ROE:  42.3% | P/E:  30.2
INFY         | ROE:  31.5% | P/E:  27.8
HDFCBANK     | ROE:  17.8% | P/E:  19.5
ICICIBANK    | ROE:  18.2% | P/E:  18.3

JSON Output Conversion

Convert console output to JSON for programmatic use:
#!/usr/bin/env python3
import json
import sys
from single_stock_analyzer import analyze_stock

# Modify single_stock_analyzer.py to return dict instead of print
# Or parse stdout with regex

def analyze_to_json(symbol):
    # This requires modifying single_stock_analyzer.py
    # to return a dictionary instead of printing
    data = {
        "symbol": symbol,
        "net_profit_latest": 18200.0,
        "qoq_np": 5.51,
        "yoy_np": 13.04,
        # ... etc
    }
    return data

if __name__ == "__main__":
    symbol = sys.argv[1]
    result = analyze_to_json(symbol)
    print(json.dumps(result, indent=2))

Limitations

  1. No Technical Indicators: This script only analyzes fundamental data. For technical analysis (RSI, SMA, RVOL), use the full pipeline output.
  2. No OHLCV Data: Price history, returns, and ATH are not available. Use ohlcv_data/{SYMBOL}.csv for price data.
  3. Historical P/E Not Available: The script shows “Data Unavailable” for 5-year historical P/E.
  4. Static Snapshot: Analyzes data from fundamental_data.json - run fetch_fundamental_data.py to refresh.
  5. No News/Events: Corporate actions, announcements, and news are not included. See full pipeline output for these.

Advanced Usage

Modify Calculation Logic

Edit single_stock_analyzer.py to add custom metrics:
# Add Price-to-Book ratio
book_value_per_share = get_value_from_pipe_string(bs_c.get("TOTAL_EQUITY"), 0) / total_shares
price = pe * ttm_eps  # Back-calculate price from PE
pb_ratio = price / book_value_per_share if book_value_per_share > 0 else 0.0

print(f"P/B Ratio: {pb_ratio:.2f}")

Integration with Full Pipeline

Use as a validation step after pipeline completion:
#!/bin/bash
# Run pipeline then spot-check a few stocks

python3 run_full_pipeline.py

echo "\n=== Spot Check: Top 5 by Market Cap ==="
for stock in RELIANCE TCS HDFCBANK INFY BHARTIARTL
do
    echo "\n--- $stock ---"
    python3 single_stock_analyzer.py $stock | grep -E "(Latest Quarter|YoY|ROE)"
done

Troubleshooting

”fundamental_data.json not found”

Solution: Fetch the data first:
python3 fetch_dhan_data.py
python3 fetch_fundamental_data.py

“Stock ‘XYZ’ not found in database”

Causes:
  • Incorrect symbol (check NSE symbol, not company name)
  • Stock recently listed (not in database yet)
  • Stock delisted
Solution: Verify symbol on NSE website or run:
python3 -c "import json; data=json.load(open('fundamental_data.json')); print([s['Symbol'] for s in data if 'HDFC' in s['Symbol']])"

Zero Values for All Metrics

Cause: Stock exists but has no fundamental data (e.g., newly listed or suspended) Solution: Check if stock is actively traded and has filed quarterly results.

Next Steps

Build docs developers (and LLMs) love