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

Add, remove, search an item in listview in C#

Below is the C# code which will help you to add, remove and search operations on listview control in C#. Below is the design 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 Treeview_control_demo {     public partial class Form2 : Form     {         public Form2()         {             InitializeComponent();             listView1.View = View.Details;                   }         private void button1_Click(object sender, EventArgs e)         {             if (textBox1.Text.Trim().Length == 0)...

display files and directories in Listview

Below is the C# code which displays all files and directories in listview control with their file size and creation date. If it is file then it also displays the extension of the file e.g. .txt, .jpg etc Below is the design view of the project: Listview to display files and directories with size and date created 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; using System.IO; namespace search_in_listview {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();                   }         private void button1_Click(object sender, EventArgs ...

Add worklog in Jira using Python

 Below is the Python code to add the worklog in Jira. You need to install a request library for this. Here is the code: import requests from requests.auth import HTTPBasicAuth import json url = "https://your jira address here/rest/api/2/issue/ticket_number/worklog" auth = HTTPBasicAuth("username", "jira access token") headers = {     "Accept": "application/json",     "Content-Type": "application/json" } payload = json.dumps({     "comment": {         "content": [             {                 "content": [                     {                         "text": "This is for QA Testing",                         "type": "text"                     } ...