Skip to main content

NSE Stock Fundamental Analysis in Python

 NSE Stock Fundamental Analysis in Python with yfinance library. Here is the full code:


import random

import time

from tqdm import tqdm

import yfinance as yf

import pandas as pd

from datetime import datetime, timedelta



def get_nifty50_symbols():

    nifty50_symbols = ["ACC", "PRSMJOHNSN", "AETHER"]

    return [symbol + ".NS" for symbol in nifty50_symbols]



def get_all_indian_stocks():

    # Fetch list of Indian Stocks

    url = f".\\Nifty_Stocks_Anaysis.csv"

    df = pd.read_csv(url)

    symbols = df['SYMBOL'].tolist()

    return [symbol + ".NS" for symbol in symbols]



def get_stock_data(symbol):

    stock = yf.Ticker(symbol)

    # Get price data

    end_date = datetime.now()

    start_date = end_date - timedelta(days=365)

    price_data = stock.history(start=start_date, end=end_date)


    if price_data.empty:

        return None


    latest_price = price_data.iloc[-1]


    # Calculate percentage changes

    daily_change = (latest_price['Close'] - price_data.iloc[-2]['Close']) / price_data.iloc[-2]['Close'] * 100

    weekly_change = (latest_price['Close'] - price_data.iloc[-2]['Close']) / price_data.iloc[-6]['Close'] * 100

    monthly_change = (latest_price['Close'] - price_data.iloc[-2]['Close']) / price_data.iloc[-22]['Close'] * 100


    # Get Fundamental Data

    info = stock.info


    stock_data = {

        'Symbol': symbol,

        'Company Name': info.get('longName', 'N/A'),

        'Sector': info.get('sector', 'N/A'),

        'Industry': info.get('industry', 'N/A'),

        'Market Cap': info.get('marketcap', 'N/A'),

        'P/E Ratio': info.get('trailingPE', 'N/A'),

        'Forward P/E': info.get('forwardPE', 'N/A'),

        'PEG Ratio': info.get('pegRatio', 'N/A'),

        'Price to Book': info.get('priceToBook', 'N/A'),

        'EV/EBITDA': info.get('enterpriseToEbitda', 'N/A'),

        'Profit Margin': info.get('profitMargins', 'N/A'),

        'Operating Margin': info.get('operatingMargins', 'N/A'),

        'ROE': info.get('returnOnEquity', 'N/A'),

        'ROA': info.get('returnOnAssets', 'N/A'),

        'Revenue': info.get('totalRevenue', 'N/A'),

        'Revenue Per Share': info.get('revenuePerShare', 'N/A'),

        'Quarterly Revenue Growth': info.get('quarterlyRevenueGrowth', 'N/A'),

        'Gross Profit': info.get('grossProfits', 'N/A'),

        'EBITDA': info.get('ebitda', 'N/A'),

        'Net Income': info.get('netIncomeToCommon', 'N/A'),

        'EPS': info.get('trailingEps', 'N/A'),

        'Quarterly Earnings Growth': info.get('quarterlyEarningsGrowth', 'N/A'),

        'Total Cash': info.get('totalCash', 'N/A'),

        'Total Debt': info.get('totalDebt', 'N/A'),

        'Debt To Equity': info.get('debtToEquity', 'N/A'),

        'Current Ratio': info.get('currentRatio', 'N/A'),

        'Book Value': info.get('bookValue', 'N/A'),

        'Free Cash Flow': info.get('freeCashFlow', 'N/A'),

        'Dividend Rate': info.get('dividendRate', 'N/A'),

        'Dividend Yield': info.get('dividendYield', 'N/A    '),

        'Payout Ratio': info.get('payoutRatio', 'N/A'),

        'Beta': info.get('beta', 'N/A'),

        '52 Week High': info.get('fiftyTwoWeekHigh', 'N/A'),

        '52 Week Low': info.get('fiftyTwoWeekLow', 'N/A'),

        '50 Day Average': info.get('fiftyDayAverage', 'N/A'),

        '200 Day Average': info.get('twoHundredDayAverage', 'N/A'),

        'Daily Change %': f"{daily_change:.2f}%",

        'Weekly Change %': f"{weekly_change:.2f}%",

        'Monthly Change %': f"{monthly_change:.2f}%",

        'Volume': latest_price['Volume']

    }

    return stock_data



def main():

    """

    nifty50_symbols = get_nifty50_symbols()


    all_stock_data = []


    for symbol in nifty50_symbols:

        print(f"Fetching data for {symbol}...")

        try:

            stock_data = get_stock_data(symbol)

            if stock_data:

                all_stock_data.append(stock_data)

                print(f"Data Fetched successfully for {symbol}")

            else:

                print(f"No data available for {symbol}")

        except Exception as e:

            print(f"Error fetching data for {symbol} : {str(e)}")

            all_stock_data.append({'Symbol': symbol, 'Error': str(e)})


    # Convert to Dataframe and Save to CSV

    df = pd.DataFrame(all_stock_data)

    csv_file = 'nifty50_stock_data.csv'

    df.to_csv(csv_file, index=False)

    print(f"Data Saved to CSV file {csv_file}")

"""

    all_symbols = get_all_indian_stocks()

    print(f"Total Number of Stocks: {len(all_symbols)}")


    all_stock_data = []


    # Create a tqdm Progress Bar

    pbar = tqdm(total=len(all_symbols), desc="Processing Stocks", unit="stock")


    for symbol in all_symbols:

        try:

            stock_data = get_stock_data(symbol)

            if stock_data:

                all_stock_data.append(stock_data)

                pbar.set_postfix_str(f"Fetched Data for Symbol {symbol}")

            else:

                pbar.set_postfix_str(f"No Data Available for Symbol {symbol}")

        except Exception as e:

            pbar.set_postfix_str(f"Error fetching data for {symbol} : {str(e)}")

            all_stock_data.append({'Symbol': symbol, 'Error': str(e)})


        # Update the progress bar

        pbar.update(1)


        # add a small random delay between request

        time.sleep(random.uniform(1, 3))


    # Close the progress bar

    pbar.close()


    # Save all data to a single CSV file

    df = pd.DataFrame(all_stock_data)

    csv_file = 'all_indian_stocks_data.csv'

    df.to_csv(csv_file, index=False)

    print(f"Data Saved to CSV file {csv_file}")


    print(f"All stocks are processed and saved to a single csv file ")



if __name__ == '__main__':

    main()


"""


name_of_file = f"./All_Stocks_Anaysis_9_Sep_2024_5_Days.xlsx"

data = pd.read_excel(name_of_file)


required_colum_name = "Stock_Symbol"

print(data[required_colum_name])


ticker = yf.Ticker('ADANIPOWER.nse')


print(dir(ticker))


for k, v in ticker.info.items():

    print(k, '\t', v, '\n')

"""

Comments

Popular posts from this blog

RGB Color Demo in C# using scrollbar as a slider horizontally

Below is the project which contains 3 horizontal scrollbars if we slides the scrollbars the background color of the form is changing accordingly. first scrollbar is adding red color, second adding green and third one adding blue upon scrolling or sliding. Take 3 horizontal scrollbars and assign them maximum value of 255(from 0) to each one. Below is the designer view of the project: Below is the source code of the project: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Color_RGB_demo {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();                   }         public...

MULTIPLEXER , Design & Implement the given 4 variable function using IC74LS153. Verify its Truth-Table

TITLE: MULTIPLEXER   AIM: Design & Implement the given 4 variable function using IC74LS153. Verify its Truth-Table.   LEARNING OBJECTIVE: ·        To learn about IC 74153 and its internal structure. ·        To realize 8:1 MUX and 16:1 MUX using IC 74153.   COMPONENTS REQUIRED: IC 74153, IC 7404, IC 7432, CDS, wires, Power supply. IC PINOUT:            1)     IC 74153 2)      IC 7404:                                              3) IC 7432 THEORY:   ·        Multiplexer is a combinational circuit that is one of the most widely used in digital design. ·        The multiplexer is a data selector which gates one out of several inputs to a sin...

Get/Access JIRA/JIRA API data using python

 Below is the program which will guide you on how to access the JIRA API data using python. First, you need to create a token for JIRA. You need to install the following libraries using the following commands: pip install requests pip install json-excel-converter And the code is: # Import the required libraries import requests from requests.auth import HTTPBasicAuth import json import pandas as pd from json_excel_converter import Converter from json_excel_converter.xlsx import Writer # URL to Search all issues. url = "YOUR JIRA URL" # Create an authentication object,using # registered emailID, and, token received. auth = HTTPBasicAuth("email-d",                      "jira token created") # The Header parameter, should mention, the # desired format of data. headers = {     "Accept": "application/json" } # Mention the JQL query. # Here, all issues, of a project, are # fetched,as,no criteria is mentioned. query = { ...