Baskar2005 commited on
Commit
c6b4b12
1 Parent(s): 08d4da2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +263 -0
app.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import yfinance as yf
4
+ from niftystocks import ns
5
+ from openai import AzureOpenAI
6
+ import os
7
+ # Create a Streamlit app
8
+ st.title("NIFTY Finance Analysis")
9
+
10
+
11
+ # Function to fetch financial data
12
+ def get_financial_data(ticker):
13
+ company = yf.Ticker(ticker)
14
+ financial_data = {}
15
+
16
+ # Price Ratios
17
+ financial_data['price_to_earnings'] = company.info.get('trailingPE')
18
+ financial_data['price_to_book'] = company.info.get('priceToBook')
19
+
20
+ # Debt
21
+ financial_data['debt_to_equity'] = company.info.get('debtToEquity')
22
+
23
+ # Financial Statements
24
+ financial_data['balance_sheet'] = company.balance_sheet
25
+ financial_data['income_statement'] = company.financials
26
+ financial_data['cashflow_statement'] = company.cashflow
27
+
28
+ # Management Quality
29
+ financial_data['management'] = company.info.get('management')
30
+
31
+ # Financial Ratios
32
+ financial_data['current_ratio'] = company.info.get('currentRatio')
33
+ financial_data['dividend_yield'] = company.info.get('dividendYield')
34
+ financial_data['return_on_equity'] = company.info.get('returnOnEquity')
35
+
36
+ # Other metrics
37
+ financial_data['market_cap'] = company.info.get('marketCap')
38
+ financial_data['earnings_growth'] = company.info.get('earningsGrowth')
39
+ financial_data['return_on_assets'] = company.info.get('returnOnAssets')
40
+ financial_data['enterprise_value'] = company.info.get('enterpriseValue')
41
+ financial_data['recommendation_mean'] = company.info.get('recommendationMean')
42
+ financial_data['beta'] = company.info.get('beta')
43
+ financial_data['book_value'] = company.info.get('bookValue')
44
+ financial_data['free_cashflow'] = company.info.get('freeCashflow')
45
+ financial_data['revenue_growth'] = company.info.get('revenueGrowth')
46
+ financial_data['trailing_eps'] = company.info.get('trailingEps')
47
+ financial_data['previous_close'] = company.info.get('previousClose')
48
+ financial_data['average_volume'] = company.info.get('averageVolume')
49
+ financial_data['dividend_yield'] = company.info.get('dividendYield')
50
+ financial_data['trailing_pe'] = company.info.get('trailingPE')
51
+ financial_data['business_model'] = company.info.get('longBusinessSummary')
52
+
53
+ return financial_data
54
+
55
+ # Summarize and analyze the data
56
+ def summarize_company(ticker, data):
57
+ summary = {
58
+ "Company": ticker,
59
+ "Market Cap": data['market_cap'],
60
+ "Price to Earnings": data['price_to_earnings'],
61
+ "Price to Book": data['price_to_book'],
62
+ "Debt to Equity": data['debt_to_equity'],
63
+ "Current Ratio": data['current_ratio'],
64
+ "Dividend Yield": data['dividend_yield'],
65
+ "Return on Equity": data['return_on_equity'],
66
+ "Earnings Growth": data['earnings_growth'],
67
+ "Return on Assets": data['return_on_assets'],
68
+ "Enterprise Value": data['enterprise_value'],
69
+ "Recommendation Mean": data['recommendation_mean'],
70
+ "Beta": data['beta'],
71
+ "Book Value": data['book_value'],
72
+ "Free Cash Flow": data['free_cashflow'],
73
+ "Revenue Growth": data['revenue_growth'],
74
+ "Trailing EPS": data['trailing_eps'],
75
+ "Previous Close": data['previous_close'],
76
+ "Average Volume": data['average_volume'],
77
+ "Trailing PE": data['trailing_pe'],
78
+ "Business Model": data['business_model']
79
+ }
80
+ return summary
81
+
82
+ def summarize_text_technical(details_of_companies):
83
+ client = AzureOpenAI()
84
+ conversation = [
85
+ {"role": "system", "content": "You are a helpful assistant."},
86
+ {"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}```."}
87
+ ]
88
+
89
+ # Call OpenAI GPT-3.5-turbo
90
+ chat_completion = client.chat.completions.create(
91
+ model = "GPT-3",
92
+ messages = conversation,
93
+ max_tokens=600,
94
+ temperature=0
95
+ )
96
+
97
+ response = chat_completion.choices[0].message.content
98
+ return response
99
+
100
+ def summarize_text_fundamental(details_of_companies):
101
+ client = AzureOpenAI(api_key= "5c68e66b7eb3470987c9088b6602c6c7",
102
+ api_version="2023-07-01-preview",
103
+ azure_endpoint = "https://azureadople.openai.azure.com/"
104
+ )
105
+ conversation = [
106
+ {"role": "system", "content": "You are a helpful assistant."},
107
+ {"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}```."}
108
+ ]
109
+
110
+ # Call OpenAI GPT-3.5-turbo
111
+ chat_completion = client.chat.completions.create(
112
+ model = "GPT-3",
113
+ messages = conversation,
114
+ max_tokens=600,
115
+ temperature=0
116
+ )
117
+
118
+ response = chat_completion.choices[0].message.content
119
+ return response
120
+
121
+ # Function to fetch historical data
122
+ def fetch_stock_data(company, start_date, end_date):
123
+ stock = yf.Ticker(company)
124
+ df = stock.history(start=start_date, end=end_date)
125
+ return df
126
+
127
+ # Function to analyze price and volume changes
128
+ def analyze_data(df):
129
+ df['Open_to_High'] = df['High'] - df['Open']
130
+ df['Open_to_Low'] = df['Open'] - df['Low']
131
+ df['Open_to_Close'] = df['Close'] - df['Open']
132
+ return df
133
+
134
+ # Function to add technical indicators
135
+ def add_technical_indicators(df):
136
+ # Simple Moving Averages
137
+ df['SMA_20'] = df['Close'].rolling(window=20).mean()
138
+ df['SMA_50'] = df['Close'].rolling(window=50).mean()
139
+
140
+ # Exponential Moving Averages
141
+ df['EMA_20'] = df['Close'].ewm(span=20, adjust=False).mean()
142
+ df['EMA_50'] = df['Close'].ewm(span=50, adjust=False).mean()
143
+
144
+ # Relative Strength Index (RSI)
145
+ delta = df['Close'].diff(1)
146
+ gain = delta.where(delta > 0, 0)
147
+ loss = -delta.where(delta < 0, 0)
148
+ avg_gain = gain.rolling(window=14).mean()
149
+ avg_loss = loss.rolling(window=14).mean()
150
+ rs = avg_gain / avg_loss
151
+ df['RSI'] = 100 - (100 / (1 + rs))
152
+
153
+ # Moving Average Convergence Divergence (MACD)
154
+ df['MACD'] = df['Close'].ewm(span=12, adjust=False).mean() - df['Close'].ewm(span=26, adjust=False).mean()
155
+ df['MACD_Signal'] = df['MACD'].ewm(span=9, adjust=False).mean()
156
+
157
+ return df
158
+
159
+ # Analyze and store data for all companies
160
+ def analyze_nifty_50(companies, start_date, end_date):
161
+ result = {}
162
+ for company in companies:
163
+ df = fetch_stock_data(company+".NS", start_date, end_date)
164
+ if df.empty:
165
+ continue
166
+ df_analyzed = analyze_data(df)
167
+ df_analyzed = add_technical_indicators(df_analyzed)
168
+
169
+ result[company] = {
170
+ 'open_to_high_avg': df_analyzed['Open_to_High'].mean(),
171
+ 'open_to_low_avg': df_analyzed['Open_to_Low'].mean(),
172
+ 'open_to_close_avg': df_analyzed['Open_to_Close'].mean(),
173
+ 'average_volume': df_analyzed['Volume'].mean(),
174
+ 'historical_average_volume': df['Volume'].mean(),
175
+ 'SMA_20': df_analyzed['SMA_20'].iloc[-1],
176
+ 'SMA_50': df_analyzed['SMA_50'].iloc[-1],
177
+ 'EMA_20': df_analyzed['EMA_20'].iloc[-1],
178
+ 'EMA_50': df_analyzed['EMA_50'].iloc[-1],
179
+ 'RSI': df_analyzed['RSI'].iloc[-1],
180
+ 'MACD': df_analyzed['MACD'].iloc[-1],
181
+ 'MACD_Signal': df_analyzed['MACD_Signal'].iloc[-1]
182
+ }
183
+ return result
184
+
185
+
186
+ tabs = ["Fundamental Analysis", "Technical Analysis"]
187
+ tab = st.tabs(tabs)
188
+
189
+ with tab[0]:
190
+ # Fundamental Analysis
191
+ st.header("Fundamental Analysis")
192
+ st.info("If You Enter List of Companies Manually Not Mention '.NS' after Company Name")
193
+ fundamental_text_input = st.text_input("Enter List of Company Names",placeholder="Enter Comma Seperated List of Companies")
194
+ st.write("or")
195
+ st.write("Get Automatically Nifty 50 Companies, Click 'Run Fundamental Analysis'")
196
+ fundamental_button = st.button("Run Fundamental Analysis")
197
+ if fundamental_button:
198
+ # Fetch data for all Nifty 50 companies
199
+ if fundamental_text_input:
200
+ nifty_50_tickers = fundamental_text_input.split(",")
201
+ else:
202
+ nifty_50_tickers = ns.get_nifty50()
203
+ nifty_50_data = {ticker: get_financial_data(ticker+'.NS') for ticker in nifty_50_tickers}
204
+ details_of_companies = {}
205
+ for ticker, data in nifty_50_data.items():
206
+ details_of_companies[ticker] = summarize_company(ticker, data)
207
+
208
+ fundamental_df = pd.DataFrame(details_of_companies)
209
+ fundamental_df.drop('Company', inplace=True)
210
+ fundamental_df = fundamental_df.transpose()
211
+ fundamental_df.index.name = 'Company'
212
+ all_company_summary = ""
213
+ for ticker, data in details_of_companies.items():
214
+ all_company_summary += f"\n\n----{ticker}----"+"\n\n"+summarize_text_fundamental(data)
215
+ print(data)
216
+ fundamental_df.loc[ticker, 'summary'] = "\n\nCompany:"+ticker+"\n\n"+summarize_text_fundamental(data)
217
+ print(ticker)
218
+ summary_for_fundamental = ""
219
+ for i in range(len(all_company_summary.split("\n\n"))):
220
+ summary_for_fundamental += all_company_summary.split("\n\n")[i]+" \n\n"
221
+ # Display the results
222
+ st.write(fundamental_df)
223
+ st.download_button("Download CSV", fundamental_df.to_csv(), "nifty_50_fundamental_analysis.csv")
224
+ st.write(summary_for_fundamental)
225
+
226
+ with tab[1]:
227
+ # Technical Analysis
228
+ st.header("Technical Analysis")
229
+ st.info("If You Enter List of Companies Manually Not Mention '.NS' after Company Name")
230
+ st.info("If the Result 'difficult to make decision' it is may not good for invest.")
231
+ start_date = st.date_input("Start Date")
232
+ end_date = st.date_input("End Date")
233
+ technical_text_input = st.text_input("Enter List of Company Names ---",placeholder="Enter Comma Seperated List of Companies")
234
+ st.write("or")
235
+ st.write("Get Automatically Nifty 50 Companies, Click 'Run Technical Analysis'")
236
+ technical_button = st.button("Run Technical Analysis")
237
+ if technical_button:
238
+ # Analyze the data
239
+ if technical_text_input:
240
+ nifty_50_companies = technical_text_input.split(",")
241
+ else:
242
+ nifty_50_companies = ns.get_nifty50()
243
+ nifty_50_analysis = analyze_nifty_50(nifty_50_companies, start_date, end_date)
244
+ technical_df = pd.DataFrame(nifty_50_analysis)
245
+ technical_df = technical_df.transpose()
246
+ technical_df.index.name = 'Company'
247
+ all_company_summary = ""
248
+ for ticker, data in nifty_50_analysis.items():
249
+ print(data)
250
+ all_company_summary += f"\n\n----{ticker}----"+"\n\n"+summarize_text_technical(data)
251
+ technical_df.loc[ticker, 'summary'] = "\n\nCompany:"+ticker+"\n\n"+summarize_text_technical(data)
252
+
253
+ technical_df.to_csv("nifty_50_technical_analysis.csv")
254
+ summary_for_technical = ""
255
+
256
+ for i in range(len(all_company_summary.split("\n\n"))):
257
+ summary_for_technical +=all_company_summary.split("\n\n")[i]+" \n\n"
258
+
259
+ # Display the results
260
+ st.write(technical_df)
261
+ st.download_button("Download CSV", technical_df.to_csv(), "nifty_50_technical_analysis.csv")
262
+
263
+ st.write(summary_for_technical)