import yfinance as yf
from pymongo import MongoClient

# Connect to MongoDB
client = MongoClient("mongodb://192.168.31.176:27017")
database = client["zerodha_test"]
collection = database["bse_data1"]
# collection = database["nse_data1"]

# # Find all documents with the symbol where listing_date does not exist
documents = collection.find({"listing_date": {"$exists": False}}, {"symbol": 1, "_id": 0})

for document in documents:
    try:
        # Define the stock symbol
        # symbol = f'KPIL.BO'  # Replace with your symbol
        symbol = document['symbol']  # Replace with your symbol

        # Download the historical data for the stock
        data = yf.download(symbol, period="max")

        # Get the earliest available date
        listing_date = data.index.min()
        print(listing_date)

        # Convert the date to the format yyyy-mm-dd
        listing_date_str = listing_date.strftime('%Y-%m-%d')

        # Update the document in MongoDB to add the listing date
        collection.update_one(
            {"symbol": document["symbol"]},  # Match the document by symbol
            {"$set": {"listing_date": listing_date_str}}  # Set the new field
        )
    except (AttributeError, ValueError):
        continue

print("Listing dates updated successfully.")