Spaces:
Running
Running
import streamlit as st | |
import pandas as pd | |
import yfinance as yf | |
from niftystocks import ns | |
from openai import AzureOpenAI | |
import os | |
# Create a Streamlit app | |
st.title("NIFTY Finance Analysis") | |
# Function to fetch financial data | |
def get_financial_data(ticker): | |
company = yf.Ticker(ticker) | |
financial_data = {} | |
# Price Ratios | |
financial_data['price_to_earnings'] = company.info.get('trailingPE') | |
financial_data['price_to_book'] = company.info.get('priceToBook') | |
# Debt | |
financial_data['debt_to_equity'] = company.info.get('debtToEquity') | |
# Financial Statements | |
financial_data['balance_sheet'] = company.balance_sheet | |
financial_data['income_statement'] = company.financials | |
financial_data['cashflow_statement'] = company.cashflow | |
# Management Quality | |
financial_data['management'] = company.info.get('management') | |
# Financial Ratios | |
financial_data['current_ratio'] = company.info.get('currentRatio') | |
financial_data['dividend_yield'] = company.info.get('dividendYield') | |
financial_data['return_on_equity'] = company.info.get('returnOnEquity') | |
# Other metrics | |
financial_data['market_cap'] = company.info.get('marketCap') | |
financial_data['earnings_growth'] = company.info.get('earningsGrowth') | |
financial_data['return_on_assets'] = company.info.get('returnOnAssets') | |
financial_data['enterprise_value'] = company.info.get('enterpriseValue') | |
financial_data['recommendation_mean'] = company.info.get('recommendationMean') | |
financial_data['beta'] = company.info.get('beta') | |
financial_data['book_value'] = company.info.get('bookValue') | |
financial_data['free_cashflow'] = company.info.get('freeCashflow') | |
financial_data['revenue_growth'] = company.info.get('revenueGrowth') | |
financial_data['trailing_eps'] = company.info.get('trailingEps') | |
financial_data['previous_close'] = company.info.get('previousClose') | |
financial_data['average_volume'] = company.info.get('averageVolume') | |
financial_data['dividend_yield'] = company.info.get('dividendYield') | |
financial_data['trailing_pe'] = company.info.get('trailingPE') | |
financial_data['business_model'] = company.info.get('longBusinessSummary') | |
return financial_data | |
# Summarize and analyze the data | |
def summarize_company(ticker, data): | |
summary = { | |
"Company": ticker, | |
"Market Cap": data['market_cap'], | |
"Price to Earnings": data['price_to_earnings'], | |
"Price to Book": data['price_to_book'], | |
"Debt to Equity": data['debt_to_equity'], | |
"Current Ratio": data['current_ratio'], | |
"Dividend Yield": data['dividend_yield'], | |
"Return on Equity": data['return_on_equity'], | |
"Earnings Growth": data['earnings_growth'], | |
"Return on Assets": data['return_on_assets'], | |
"Enterprise Value": data['enterprise_value'], | |
"Recommendation Mean": data['recommendation_mean'], | |
"Beta": data['beta'], | |
"Book Value": data['book_value'], | |
"Free Cash Flow": data['free_cashflow'], | |
"Revenue Growth": data['revenue_growth'], | |
"Trailing EPS": data['trailing_eps'], | |
"Previous Close": data['previous_close'], | |
"Average Volume": data['average_volume'], | |
"Trailing PE": data['trailing_pe'], | |
"Business Model": data['business_model'] | |
} | |
return summary | |
def summarize_text_technical(details_of_companies): | |
client = AzureOpenAI() | |
conversation = [ | |
{"role": "system", "content": "You are a helpful assistant."}, | |
{"role": "user", "content": f"based on your financial knowledge to analyse the given finance data to give is the company is (good or better or bad) to investing choose the one based on given data only.give the reason why its good or better or bad.if based on data the company not good for investing boldly say is not good for investing.your decision is based on provided data only do not ask additional data to make a judgement.Output Format: Analysis: Reason:```{details_of_companies}```."} | |
] | |
# Call OpenAI GPT-3.5-turbo | |
chat_completion = client.chat.completions.create( | |
model = "GPT-3", | |
messages = conversation, | |
max_tokens=600, | |
temperature=0 | |
) | |
response = chat_completion.choices[0].message.content | |
return response | |
def summarize_text_fundamental(details_of_companies): | |
client = AzureOpenAI() | |
conversation = [ | |
{"role": "system", "content": "You are a helpful assistant."}, | |
{"role": "user", "content": f"i want detailed Summary from given finance details.give a summary for each companies detailed and include all the information of a company. finally you analyse the company data to give it's [good or better or bad] for investment. content in backticks.Give Only Summary.Output Format:Summary:summary Analysis: good or better or bad for investment.```{details_of_companies}```."} | |
] | |
# Call OpenAI GPT-3.5-turbo | |
chat_completion = client.chat.completions.create( | |
model = "GPT-3", | |
messages = conversation, | |
max_tokens=600, | |
temperature=0 | |
) | |
response = chat_completion.choices[0].message.content | |
return response | |
# Function to fetch historical data | |
def fetch_stock_data(company, start_date, end_date): | |
stock = yf.Ticker(company) | |
df = stock.history(start=start_date, end=end_date) | |
return df | |
# Function to analyze price and volume changes | |
def analyze_data(df): | |
df['Open_to_High'] = df['High'] - df['Open'] | |
df['Open_to_Low'] = df['Open'] - df['Low'] | |
df['Open_to_Close'] = df['Close'] - df['Open'] | |
return df | |
# Function to add technical indicators | |
def add_technical_indicators(df): | |
# Simple Moving Averages | |
df['SMA_20'] = df['Close'].rolling(window=20).mean() | |
df['SMA_50'] = df['Close'].rolling(window=50).mean() | |
# Exponential Moving Averages | |
df['EMA_20'] = df['Close'].ewm(span=20, adjust=False).mean() | |
df['EMA_50'] = df['Close'].ewm(span=50, adjust=False).mean() | |
# Relative Strength Index (RSI) | |
delta = df['Close'].diff(1) | |
gain = delta.where(delta > 0, 0) | |
loss = -delta.where(delta < 0, 0) | |
avg_gain = gain.rolling(window=14).mean() | |
avg_loss = loss.rolling(window=14).mean() | |
rs = avg_gain / avg_loss | |
df['RSI'] = 100 - (100 / (1 + rs)) | |
# Moving Average Convergence Divergence (MACD) | |
df['MACD'] = df['Close'].ewm(span=12, adjust=False).mean() - df['Close'].ewm(span=26, adjust=False).mean() | |
df['MACD_Signal'] = df['MACD'].ewm(span=9, adjust=False).mean() | |
return df | |
# Analyze and store data for all companies | |
def analyze_nifty_50(companies, start_date, end_date): | |
result = {} | |
for company in companies: | |
df = fetch_stock_data(company+".NS", start_date, end_date) | |
if df.empty: | |
continue | |
df_analyzed = analyze_data(df) | |
df_analyzed = add_technical_indicators(df_analyzed) | |
result[company] = { | |
'open_to_high_avg': df_analyzed['Open_to_High'].mean(), | |
'open_to_low_avg': df_analyzed['Open_to_Low'].mean(), | |
'open_to_close_avg': df_analyzed['Open_to_Close'].mean(), | |
'average_volume': df_analyzed['Volume'].mean(), | |
'historical_average_volume': df['Volume'].mean(), | |
'SMA_20': df_analyzed['SMA_20'].iloc[-1], | |
'SMA_50': df_analyzed['SMA_50'].iloc[-1], | |
'EMA_20': df_analyzed['EMA_20'].iloc[-1], | |
'EMA_50': df_analyzed['EMA_50'].iloc[-1], | |
'RSI': df_analyzed['RSI'].iloc[-1], | |
'MACD': df_analyzed['MACD'].iloc[-1], | |
'MACD_Signal': df_analyzed['MACD_Signal'].iloc[-1] | |
} | |
return result | |
tabs = ["Fundamental Analysis", "Technical Analysis"] | |
tab = st.tabs(tabs) | |
with tab[0]: | |
# Fundamental Analysis | |
st.header("Fundamental Analysis") | |
st.info("If You Enter List of Companies Manually Not Mention '.NS' after Company Name") | |
fundamental_text_input = st.text_input("Enter List of Company Names",placeholder="Enter Comma Seperated List of Companies") | |
st.write("or") | |
st.write("Get Automatically Nifty 50 Companies, Click 'Run Fundamental Analysis'") | |
fundamental_button = st.button("Run Fundamental Analysis") | |
if fundamental_button: | |
# Fetch data for all Nifty 50 companies | |
if fundamental_text_input: | |
nifty_50_tickers = fundamental_text_input.split(",") | |
else: | |
nifty_50_tickers = ns.get_nifty50() | |
nifty_50_data = {ticker: get_financial_data(ticker+'.NS') for ticker in nifty_50_tickers} | |
details_of_companies = {} | |
for ticker, data in nifty_50_data.items(): | |
details_of_companies[ticker] = summarize_company(ticker, data) | |
fundamental_df = pd.DataFrame(details_of_companies) | |
fundamental_df.drop('Company', inplace=True) | |
fundamental_df = fundamental_df.transpose() | |
fundamental_df.index.name = 'Company' | |
all_company_summary = "" | |
for ticker, data in details_of_companies.items(): | |
all_company_summary += f"\n\n----{ticker}----"+"\n\n"+summarize_text_fundamental(data) | |
print(data) | |
fundamental_df.loc[ticker, 'summary'] = "\n\nCompany:"+ticker+"\n\n"+summarize_text_fundamental(data) | |
print(ticker) | |
summary_for_fundamental = "" | |
for i in range(len(all_company_summary.split("\n\n"))): | |
summary_for_fundamental += all_company_summary.split("\n\n")[i]+" \n\n" | |
# Display the results | |
st.write(fundamental_df) | |
st.download_button("Download CSV", fundamental_df.to_csv(), "nifty_50_fundamental_analysis.csv") | |
st.write(summary_for_fundamental) | |
with tab[1]: | |
# Technical Analysis | |
st.header("Technical Analysis") | |
st.info("If You Enter List of Companies Manually Not Mention '.NS' after Company Name") | |
st.info("If the Result 'difficult to make decision' it is may not good for invest.") | |
start_date = st.date_input("Start Date") | |
end_date = st.date_input("End Date") | |
technical_text_input = st.text_input("Enter List of Company Names ---",placeholder="Enter Comma Seperated List of Companies") | |
st.write("or") | |
st.write("Get Automatically Nifty 50 Companies, Click 'Run Technical Analysis'") | |
technical_button = st.button("Run Technical Analysis") | |
if technical_button: | |
# Analyze the data | |
if technical_text_input: | |
nifty_50_companies = technical_text_input.split(",") | |
else: | |
nifty_50_companies = ns.get_nifty50() | |
nifty_50_analysis = analyze_nifty_50(nifty_50_companies, start_date, end_date) | |
technical_df = pd.DataFrame(nifty_50_analysis) | |
technical_df = technical_df.transpose() | |
technical_df.index.name = 'Company' | |
all_company_summary = "" | |
for ticker, data in nifty_50_analysis.items(): | |
print(data) | |
all_company_summary += f"\n\n----{ticker}----"+"\n\n"+summarize_text_technical(data) | |
technical_df.loc[ticker, 'summary'] = "\n\nCompany:"+ticker+"\n\n"+summarize_text_technical(data) | |
technical_df.to_csv("nifty_50_technical_analysis.csv") | |
summary_for_technical = "" | |
for i in range(len(all_company_summary.split("\n\n"))): | |
summary_for_technical +=all_company_summary.split("\n\n")[i]+" \n\n" | |
# Display the results | |
st.write(technical_df) | |
st.download_button("Download CSV", technical_df.to_csv(), "nifty_50_technical_analysis.csv") | |
st.write(summary_for_technical) |