import yfinance as yf
import pandas as pd
from datetime import datetime, timedelta

def find_latest_52_week_low(stocks):
    results = []

    for stock in stocks:
        try:
            # Fetch historical data for the stock
            data = yf.download(stock, start=datetime.now() - timedelta(days=365), end=datetime.now())

            if data.empty:
                print(f"No data available for {stock}")
                continue
            
            # Find the minimum close price in the last 52 weeks
            latest_52_week_low = data['Close'].min()
            latest_52_week_low_date = data[data['Close'] == latest_52_week_low].index[-1]

            # Store the result in a tuple (date, stock symbol, low price)
            results.append((latest_52_week_low_date, stock, latest_52_week_low))

        except Exception as e:
            print(f"Error fetching data for {stock}: {e}")
            print()

    # Sort results based on the date of the latest 52-week low in descending order
    results.sort(reverse=True)

    # Print results in descending order
    print("Latest 52-week lows (Descending order):")
    for result in results:
        low_date, stock_symbol, low_price = result
        print(f"Date: {low_date.date()} | Stock: {stock_symbol} | Low Price: {low_price:.2f}")

# Example usage with NIFTY 50, NXT 50, NIFTY 200, NIFTY MIDCAP 100 symbols
stock_symbols = """
AARTIIND.NS,AAVAS.NS,ABB.NS,ABCAPITAL.NS,ABFRL.NS,ACC.NS,ADANIENSOL.NS,ADANIENT.NS,
ADANIGREEN.NS,ADANIPORTS.NS,ADANIPOWER.NS,AFFLE.NS,ALKEM.NS,ALOKINDS.NS,AMBER.NS,
AMBUJACEM.NS,ANGELONE.NS,APARINDS.NS,APLAPOLLO.NS,APOLLOHOSP.NS,APOLLOTYRE.NS,
ARE&M.NS,ASHOKLEY.NS,ASIANPAINT.NS,ASTRAL.NS,ATGL.NS,AUBANK.NS,AUROPHARMA.NS,
AXISBANK.NS,BAJAJ-AUTO.NS,BAJAJFINSV.NS,BAJAJHLDNG.NS,BAJFINANCE.NS,BALKRISIND.NS,
BANDHANBNK.NS,BANKBARODA.NS,BANKINDIA.NS,BDL.NS,BEL.NS,BERGEPAINT.NS,BHARATFORG.NS,
BHARTIARTL.NS,BHEL.NS,BIOCON.NS,BLS.NS,BLUESTARCO.NS,BOSCHLTD.NS,BPCL.NS,
BRITANNIA.NS,BSE.NS,BSOFT.NS,CAMS.NS,CANBK.NS,CANFINHOME.NS,CASTROLIND.NS,CDSL.NS,
CEATLTD.NS,CENTRALBK.NS,CENTURYTEX.NS,CESC.NS,CGPOWER.NS,CHAMBLFERT.NS,CHOLAFIN.NS,
CIEINDIA.NS,CIPLA.NS,COALINDIA.NS,COCHINSHIP.NS,COFORGE.NS,COLPAL.NS,CONCOR.NS,
CREDITACC.NS,CROMPTON.NS,CUB.NS,CUMMINSIND.NS,CYIENT.NS,DABUR.NS,DALBHARAT.NS,
DATAPATTNS.NS,DEEPAKNTR.NS,DELHIVERY.NS,DIVISLAB.NS,DIXON.NS,DLF.NS,DMART.NS,
DRREDDY.NS,EICHERMOT.NS,EQUITASBNK.NS,ESCORTS.NS,EXIDEIND.NS,FACT.NS,FEDERALBNK.NS,
FINCABLES.NS,FIVESTAR.NS,FORTIS.NS,FSL.NS,GAIL.NS,GESHIP.NS,GLAND.NS,GLENMARK.NS,
GMDCLTD.NS,GMRINFRA.NS,GNFC.NS,GODREJCP.NS,GODREJPROP.NS,GRAPHITE.NS,GRASIM.NS,
GSPL.NS,GUJGASLTD.NS,HAL.NS,HAPPSTMNDS.NS,HAVELLS.NS,HCLTECH.NS,HDFCAMC.NS,
HDFCBANK.NS,HDFCLIFE.NS,HEROMOTOCO.NS,HFCL.NS,HINDALCO.NS,HINDCOPPER.NS,
HINDPETRO.NS,HINDUNILVR.NS,HONASA.NS,HSCL.NS,HUDCO.NS,ICICIBANK.NS,ICICIGI.NS,
ICICIPRULI.NS,IDBI.NS,IDEA.NS,IDFC.NS,IDFCFIRSTB.NS,IEX.NS,IGL.NS,IIFL.NS,
INDHOTEL.NS,INDIAMART.NS,INDIANB.NS,INDIGO.NS,INDUSINDBK.NS,INDUSTOWER.NS,INFY.NS,
INTELLECT.NS,IOB.NS,IOC.NS,IPCALAB.NS,IRB.NS,IRCON.NS,IRCTC.NS,IRFC.NS,ITC.NS,
ITI.NS,J&KBANK.NS,JBCHEPHARM.NS,JBMA.NS,JINDALSTEL.NS,JIOFIN.NS,JSWENERGY.NS,
JSWINFRA.NS,JSWSTEEL.NS,JUBLFOOD.NS,JYOTHYLAB.NS,KALYANKJIL.NS,KARURVYSYA.NS,
KEC.NS,KOTAKBANK.NS,KPITTECH.NS,LALPATHLAB.NS,LAURUSLABS.NS,LICHSGFIN.NS,LICI.NS,
LODHA.NS,LT.NS,LTF.NS,LTIM.NS,LTTS.NS,LUPIN.NS,M&M.NS,M&MFIN.NS,MAHABANK.NS,
MANAPPURAM.NS,MANKIND.NS,MARICO.NS,MARUTI.NS,MAXHEALTH.NS,MAZDOCK.NS,MCX.NS,
MEDANTA.NS,MFSL.NS,MGL.NS,MOTHERSON.NS,MPHASIS.NS,MRF.NS,MRPL.NS,NAM-INDIA.NS,
NATCOPHARM.NS,NATIONALUM.NS,NAUKRI.NS,NAVINFLUOR.NS,NBCC.NS,NCC.NS,NESTLEIND.NS,
NH.NS,NHPC.NS,NLCINDIA.NS,NMDC.NS,NSLNISP.NS,NTPC.NS,NYKAA.NS,OBEROIRLTY.NS,
OFSS.NS,OIL.NS,OLECTRA.NS,ONGC.NS,PAGEIND.NS,PATANJALI.NS,PAYTM.NS,PEL.NS,
PERSISTENT.NS,PETRONET.NS,PFC.NS,PIDILITIND.NS,PIIND.NS,PNB.NS,PNBHOUSING.NS,
POLICYBZR.NS,POLYCAB.NS,POONAWALLA.NS,POWERGRID.NS,PPLPHARMA.NS,PRAJIND.NS,
PRESTIGE.NS,PVRINOX.NS,RADICO.NS,RAYMOND.NS,RBLBANK.NS,RECLTD.NS,REDINGTON.NS,
RELIANCE.NS,RENUKA.NS,RITES.NS,RKFORGE.NS,RRKABEL.NS,RVNL.NS,SAIL.NS,SBICARD.NS,
SBILIFE.NS,SBIN.NS,SHREECEM.NS,SHRIRAMFIN.NS,SHYAMMETL.NS,SIEMENS.NS,SJVN.NS,
SONACOMS.NS,SONATSOFTW.NS,SRF.NS,SUNPHARMA.NS,SUNTV.NS,SUPREMEIND.NS,SUZLON.NS,
SWANENERGY.NS,SYNGENE.NS,TANLA.NS,TATACHEM.NS,TATACOMM.NS,TATACONSUM.NS,
TATAELXSI.NS,TATAINVEST.NS,TATAMOTORS.NS,TATAMTRDVR.NS,TATAPOWER.NS,TATASTEEL.NS,
TATATECH.NS,TCS.NS,TECHM.NS,TEJASNET.NS,TIINDIA.NS,TITAGARH.NS,TITAN.NS,
TORNTPHARM.NS,TORNTPOWER.NS,TRENT.NS,TRIDENT.NS,TRITURBINE.NS,TTML.NS,
TVSMOTOR.NS,UCOBANK.NS,UJJIVANSFB.NS,ULTRACEMCO.NS,UNIONBANK.NS,UNITDSPR.NS,
UPL.NS,VBL.NS,VEDL.NS,VOLTAS.NS,WELSPUNLIV.NS,WIPRO.NS,YESBANK.NS,ZEEL.NS,
ZENSARTECH.NS,ZOMATO.NS,ZYDUSLIFE.NS
"""

stock_list = [symbol.strip() for symbol in stock_symbols.split(",")]

print(len(stock_list))
find_latest_52_week_low(stock_list)
