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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#!/usr/bin/env python3
"""
Download the full list of NSE + BSE listed companies with their sectors.
Saves the result as data/indian_stocks.json

This script fetches data from:
1. NSE India (all equity securities)
2. Groups them by industry/sector
"""

import requests
import json
import csv
import io
import time

OUTPUT_FILE = "data/indian_stocks.json"


def fetch_nse_stocks() -> list[dict]:
    """
    Fetch all listed equities from NSE India.
    NSE provides a CSV at their website.
    """
    print("📥 Fetching NSE equity list...")

    url = "https://nsearchives.nseindia.com/content/equities/EQUITY_L.csv"

    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
        "Accept": "text/csv,text/html,application/xhtml+xml",
    }

    try:
        response = requests.get(url, headers=headers, timeout=30)
        response.raise_for_status()

        reader = csv.DictReader(io.StringIO(response.text))
        stocks = []
        for row in reader:
            symbol = row.get("SYMBOL", "").strip()
            name = row.get("NAME OF COMPANY", "").strip()

            if symbol and name:
                stocks.append({
                    "symbol": symbol,
                    "name": name,
                    "exchange": "NSE",
                    "yahoo_ticker": f"{symbol}.NS",
                })

        print(f"   ✅ Found {len(stocks)} NSE stocks")
        return stocks

    except Exception as e:
        print(f"   ⚠️ NSE download failed: {e}")
        print("   Trying alternative source...")
        return []


def fetch_nse_stocks_alternative() -> list[dict]:
    """
    Alternative: Fetch from NSE's JSON API.
    """
    print("📥 Trying NSE JSON API...")

    session = requests.Session()
    session.headers.update({
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
        "Accept": "application/json",
    })

    # First hit the main page to get cookies
    try:
        session.get("https://www.nseindia.com", timeout=10)
        time.sleep(1)

        # Then fetch the stock listing
        url = "https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O"
        response = session.get(url, timeout=10)

        if response.status_code == 200:
            data = response.json()
            stocks = []
            for item in data.get("data", []):
                symbol = item.get("symbol", "")
                if symbol:
                    stocks.append({
                        "symbol": symbol,
                        "name": item.get("meta", {}).get("companyName", symbol),
                        "exchange": "NSE",
                        "yahoo_ticker": f"{symbol}.NS",
                        "industry": item.get("meta", {}).get("industry", ""),
                    })
            print(f"   ✅ Found {len(stocks)} stocks from F&O list")
            return stocks
    except Exception as e:
        print(f"   ⚠️ NSE JSON API failed: {e}")

    return []


def fetch_industry_mapping() -> dict[str, str]:
    """
    Try to get industry/sector mapping for NSE stocks.
    Uses NSE's industry listing page.
    """
    print("📥 Fetching industry mapping...")

    session = requests.Session()
    session.headers.update({
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
    })

    industries = {}

    # NSE sector indices - we can use these to map stocks to sectors
    sector_indices = [
        "NIFTY BANK", "NIFTY IT", "NIFTY PHARMA", "NIFTY AUTO",
        "NIFTY FINANCIAL SERVICES", "NIFTY FMCG", "NIFTY METAL",
        "NIFTY REALTY", "NIFTY ENERGY", "NIFTY INFRASTRUCTURE",
        "NIFTY PSE", "NIFTY MEDIA", "NIFTY PRIVATE BANK",
        "NIFTY COMMODITIES", "NIFTY HEALTHCARE INDEX",
        "NIFTY CONSUMER DURABLES", "NIFTY OIL & GAS",
    ]

    try:
        session.get("https://www.nseindia.com", timeout=10)
        time.sleep(1)

        for index_name in sector_indices:
            try:
                encoded = requests.utils.quote(index_name)
                url = f"https://www.nseindia.com/api/equity-stockIndices?index={encoded}"
                response = session.get(url, timeout=10)

                if response.status_code == 200:
                    data = response.json()
                    sector = index_name.replace("NIFTY ", "").title()
                    for item in data.get("data", []):
                        symbol = item.get("symbol", "")
                        if symbol and symbol != "NIFTY BANK":
                            industries[symbol] = sector

                time.sleep(0.5)  # Be nice to the API
            except Exception:
                pass

        print(f"   ✅ Got sector mapping for {len(industries)} stocks")
    except Exception as e:
        print(f"   ⚠️ Industry mapping failed: {e}")

    return industries


# Manual overrides for top companies that keyword matching gets wrong
COMPANY_SECTOR_OVERRIDES = {
    # Conglomerates / Holding
    "RELIANCE": "Energy", "ADANIENT": "Infrastructure", "ADANIPORTS": "Logistics",
    "ADANIGREEN": "Energy", "ADANIPOWER": "Energy", "ADANITRANS": "Energy",
    "LT": "Infrastructure", "GRASIM": "Chemicals", "GODREJCP": "FMCG",
    "GODREJPROP": "Real Estate", "GODREJIND": "Chemicals",
    # Banking that keyword might miss
    "BAJFINANCE": "Banking", "BAJAJFINSV": "Banking", "CHOLAFIN": "Banking",
    "SHRIRAMFIN": "Banking", "MUTHOOTFIN": "Banking", "MANAPPURAM": "Banking",
    "PEL": "Banking", "LICHSGFIN": "Banking", "CANFINHOME": "Banking",
    "IDFCFIRSTB": "Banking", "INDUSINDBK": "Banking",
    # IT companies with non-obvious names
    "INFY": "IT", "WIPRO": "IT", "TCS": "IT", "HCLTECH": "IT", "TECHM": "IT",
    "LTIM": "IT", "LTTS": "IT", "PERSISTENT": "IT", "COFORGE": "IT",
    "MPHASIS": "IT", "TATAELXSI": "IT", "OFSS": "IT", "NAUKRI": "IT",
    "ROUTE": "IT", "HAPPSTMNDS": "IT", "MASTEK": "IT", "SONATA": "IT",
    # Pharma companies
    "CIPLA": "Pharma", "DIVISLAB": "Pharma", "DRREDDY": "Pharma",
    "SUNPHARMA": "Pharma", "LUPIN": "Pharma", "TORNTPHARM": "Pharma",
    "AUROPHARMA": "Pharma", "BIOCON": "Pharma", "ALKEM": "Pharma",
    "MAXHEALTH": "Pharma", "APOLLOHOSP": "Pharma", "LALPATHLAB": "Pharma",
    # Consumer / FMCG
    "ITC": "FMCG", "HINDUNILVR": "FMCG", "NESTLEIND": "FMCG",
    "BRITANNIA": "FMCG", "TATACONSUM": "FMCG", "DABUR": "FMCG",
    "MARICO": "FMCG", "COLPAL": "FMCG", "EMAMILTD": "FMCG",
    "PATANJALI": "FMCG", "PAGEIND": "Textiles", "TITAN": "Retail",
    "DMART": "Retail", "TRENT": "Retail", "PVRINOX": "Media",
    # Auto
    "TATAMOTORS": "Auto", "M&M": "Auto", "MARUTI": "Auto",
    "EICHERMOT": "Auto", "BAJAJ-AUTO": "Auto", "HEROMOTOCO": "Auto",
    "ASHOKLEY": "Auto", "TVSMOTORS": "Auto", "MOTHERSON": "Auto",
    "BOSCHLTD": "Auto", "EXIDEIND": "Auto", "AMARARAJA": "Auto",
    # Defence / Aerospace
    "HAL": "Defence", "BEL": "Defence", "MAZDOCK": "Defence",
    "COCHINSHIP": "Defence", "GRSE": "Defence",
    # Metals & Mining
    "TATASTEEL": "Metal", "JSWSTEEL": "Metal", "SAIL": "Metal",
    "HINDALCO": "Metal", "VEDL": "Metal", "NMDC": "Metal",
    "JINDALSTEL": "Metal", "NATIONALUM": "Metal", "COALINDIA": "Metal",
    # Energy / Oil & Gas
    "ONGC": "Energy", "BPCL": "Energy", "IOC": "Energy", "GAIL": "Energy",
    "NTPC": "Energy", "POWERGRID": "Energy", "TATAPOWER": "Energy",
    "NHPC": "Energy", "IRFC": "Infrastructure", "RECLTD": "Energy",
    # Telecom
    "BHARTIARTL": "Telecom", "IDEA": "Telecom",
    # Cement
    "ULTRACEMCO": "Real Estate", "AMBUJACEM": "Real Estate",
    "SHREECEM": "Real Estate", "ACC": "Real Estate",
    # Insurance
    "SBILIFE": "Insurance", "HDFCLIFE": "Insurance", "ICICIPRULI": "Insurance",
    "POLICYBZR": "Insurance",
    # Fintech
    "PAYTM": "Banking", "NYKAA": "Retail", "ZOMATO": "FMCG",
    # Transport
    "IRCTC": "Logistics", "INDIGO": "Logistics",
    # Real Estate
    "DLF": "Real Estate", "OBEROIRLTY": "Real Estate",
    # Chemicals
    "PIDILITIND": "Chemicals", "SRF": "Chemicals", "BERGEPAINT": "Chemicals",
    "ASIANPAINT": "Chemicals",
    # Electronics / Consumer Durables  
    "HAVELLS": "Consumer Durables", "VOLTAS": "Consumer Durables",
    "BLUESTARLT": "Consumer Durables", "CROMPTON": "Consumer Durables",
    "DIXON": "Consumer Durables",
}


def get_sector_from_name(company_name: str, symbol: str = "") -> str:
    """
    Guess the sector from the company name using keywords.
    First checks manual overrides, then uses expanded keyword matching.
    """
    # Check manual overrides first
    if symbol and symbol in COMPANY_SECTOR_OVERRIDES:
        return COMPANY_SECTOR_OVERRIDES[symbol]

    name_lower = company_name.lower()

    sector_keywords = {
        "Banking": ["bank", "finance", "financial", "credit", "lending", "capital", "invest",
                     "fund", "wealth", "asset", "nidhi", "microfinance", "nbfc", "housing fin"],
        "IT": ["tech", "software", "computer", "info", "digital", "cyber", "data", "cloud",
               "system", "solution", "consult", "internet", "e-comm", "online"],
        "Pharma": ["pharma", "drug", "med", "health", "hospital", "bio", "life science",
                    "therapeutic", "diagnos", "laborator", "path lab", "clinic", "care"],
        "Auto": ["motor", "auto", "vehicle", "car", "tyre", "tire", "tractor", "scooter",
                 "bike", "two wheel", "three wheel"],
        "FMCG": ["consumer", "food", "beverage", "dairy", "biscuit", "tea", "coffee", "soap",
                  "personal care", "nutrition", "snack", "spice", "edible", "flour", "rice"],
        "Energy": ["power", "energy", "electric", "solar", "wind", "oil", "gas", "petro",
                    "coal", "renewable", "thermal", "hydro", "nuclear", "refiner"],
        "Metal": ["steel", "iron", "metal", "alumin", "copper", "zinc", "mining", "ore",
                   "alloy", "foundry", "smelt", "casting", "forg"],
        "Telecom": ["telecom", "communication", "mobile", "wireless", "network", "broadband",
                     "fibre", "tower", "satellite"],
        "Real Estate": ["realty", "estate", "housing", "property", "construction", "infra",
                         "build", "cement", "concrete", "ceramics", "tile", "sanitary",
                         "marble", "granite"],
        "Chemicals": ["chem", "fertilizer", "pesticide", "paint", "dye", "pigment", "adhesive",
                       "polymer", "plastic", "resin", "specialty chem", "agrochem", "coating"],
        "Textiles": ["textile", "fabric", "cotton", "garment", "apparel", "silk", "wool",
                      "yarn", "weaving", "spinning", "denim", "fashion"],
        "Media": ["media", "entertainment", "film", "broadcast", "publish", "news", "print",
                   "advertising", "digital media", "content", "animation", "gaming"],
        "Insurance": ["insurance", "assurance", "life insur", "general insur"],
        "Agriculture": ["agri", "seed", "crop", "plantation", "sugar", "farm", "fertili",
                         "irrigation", "horticulture"],
        "Logistics": ["logistics", "transport", "shipping", "warehouse", "cargo", "port",
                       "courier", "express", "supply chain", "aviation", "airline", "railway"],
        "Retail": ["retail", "mart", "store", "shop", "mall", "e-commerce", "jewel",
                    "gold", "diamond", "gem", "ornament", "watch", "luxury"],
        "Hotels": ["hotel", "hospitality", "tourism", "travel", "restaurant", "resort",
                    "catering", "food service"],
        "Paper": ["paper", "packaging", "carton", "pulp", "corrugat", "box", "container"],
        "Defence": ["defence", "defense", "weapon", "ammunition", "aerospace", "shipbuild",
                     "naval", "ordnance", "missile"],
        "Consumer Durables": ["appliance", "electronic", "electrical", "lamp", "light",
                               "fan", "air condition", "refrig", "washing", "kitchen"],
        "Education": ["education", "school", "university", "learning", "coaching", "academy",
                       "training", "skill"],
    }

    for sector, keywords in sector_keywords.items():
        for keyword in keywords:
            if keyword in name_lower:
                return sector

    return "General"


def build_full_stock_list():
    """
    Build the complete stock list with sectors.
    """
    # Step 1: Fetch all NSE stocks
    nse_stocks = fetch_nse_stocks()

    if not nse_stocks:
        nse_stocks = fetch_nse_stocks_alternative()

    if not nse_stocks:
        print("\n❌ Could not fetch stock list from NSE. Using backup approach...")
        # Create a comprehensive list from yfinance
        print("📥 Building stock list from known indices...")
        nse_stocks = build_from_known_lists()

    # Step 2: Try to get industry mapping
    industry_map = fetch_industry_mapping()

    # Step 3: Assign industries to all stocks
    for stock in nse_stocks:
        symbol = stock["symbol"]
        if symbol in industry_map:
            stock["sector"] = industry_map[symbol]
        elif "industry" in stock and stock["industry"]:
            stock["sector"] = stock["industry"]
        else:
            stock["sector"] = get_sector_from_name(stock["name"], symbol)

    # Step 4: Build sector summary
    sectors = {}
    for stock in nse_stocks:
        sector = stock["sector"]
        if sector not in sectors:
            sectors[sector] = []
        sectors[sector].append(stock["symbol"])

    # Step 5: Save
    output = {
        "metadata": {
            "total_stocks": len(nse_stocks),
            "total_sectors": len(sectors),
            "generated_at": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
            "exchanges": ["NSE", "BSE"],
        },
        "stocks": nse_stocks,
        "sectors": {sector: symbols for sector, symbols in sorted(sectors.items())},
    }

    import os
    os.makedirs("data", exist_ok=True)

    with open(OUTPUT_FILE, "w") as f:
        json.dump(output, f, indent=2)

    print(f"\n{'=' * 60}")
    print(f"  ✅ Saved {len(nse_stocks)} stocks to {OUTPUT_FILE}")
    print(f"  📊 {len(sectors)} unique sectors found:")
    for sector, symbols in sorted(sectors.items(), key=lambda x: -len(x[1])):
        print(f"     {sector:<20}{len(symbols)} companies")
    print(f"{'=' * 60}")


def build_from_known_lists() -> list[dict]:
    """
    Fallback: Build a comprehensive list by downloading from yfinance 
    all tickers that end with .NS or .BO
    """
    import yfinance as yf

    # Get all Nifty indices to cover as many stocks as possible
    indices = [
        "^NSEI",     # Nifty 50
        "^NSMIDCP",  # Nifty Midcap
        "^CNXSC",    # Nifty Smallcap
    ]

    # Known comprehensive list of NSE tickers from major indices
    # This covers Nifty 50 + Next 50 + Midcap 150 + Smallcap 250 = ~500 stocks
    print("   Using known index constituents...")

    # We'll fetch the actual list from BSE's website which is more accessible
    url = "https://api.bseindia.com/BseIndiaAPI/api/ListofScripData/w?Group=&Atea=&Status=Active"
    headers = {
        "User-Agent": "Mozilla/5.0",
        "Accept": "application/json",
        "Referer": "https://www.bseindia.com/",
    }

    stocks = []
    try:
        response = requests.get(url, headers=headers, timeout=30)
        if response.status_code == 200:
            data = response.json()
            for item in data:
                code = item.get("SCRIP_CD", "")
                name = item.get("LONG_NAME", "") or item.get("scrip_name", "")
                nse_symbol = item.get("NSE_SYMBOL", "")

                if name:
                    stock = {
                        "symbol": nse_symbol if nse_symbol else str(code),
                        "name": name,
                        "exchange": "BSE" if not nse_symbol else "NSE+BSE",
                        "bse_code": str(code),
                    }
                    if nse_symbol:
                        stock["yahoo_ticker"] = f"{nse_symbol}.NS"
                    else:
                        stock["yahoo_ticker"] = f"{code}.BO"
                    stocks.append(stock)

            print(f"   ✅ Got {len(stocks)} stocks from BSE")
            return stocks
    except Exception as e:
        print(f"   ⚠️ BSE API failed: {e}")

    return stocks


if __name__ == "__main__":
    print("=" * 60)
    print("  📊 INDIAN STOCK LIST DOWNLOADER")
    print("=" * 60)
    build_full_stock_list()