Baskar2005 commited on
Commit
1551ec0
·
verified ·
1 Parent(s): 437aabf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +260 -0
app.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
102
+ conversation = [
103
+ {"role": "system", "content": "You are a helpful assistant."},
104
+ {"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}```."}
105
+ ]
106
+
107
+ # Call OpenAI GPT-3.5-turbo
108
+ chat_completion = client.chat.completions.create(
109
+ model = "GPT-3",
110
+ messages = conversation,
111
+ max_tokens=600,
112
+ temperature=0
113
+ )
114
+
115
+ response = chat_completion.choices[0].message.content
116
+ return response
117
+
118
+ # Function to fetch historical data
119
+ def fetch_stock_data(company, start_date, end_date):
120
+ stock = yf.Ticker(company)
121
+ df = stock.history(start=start_date, end=end_date)
122
+ return df
123
+
124
+ # Function to analyze price and volume changes
125
+ def analyze_data(df):
126
+ df['Open_to_High'] = df['High'] - df['Open']
127
+ df['Open_to_Low'] = df['Open'] - df['Low']
128
+ df['Open_to_Close'] = df['Close'] - df['Open']
129
+ return df
130
+
131
+ # Function to add technical indicators
132
+ def add_technical_indicators(df):
133
+ # Simple Moving Averages
134
+ df['SMA_20'] = df['Close'].rolling(window=20).mean()
135
+ df['SMA_50'] = df['Close'].rolling(window=50).mean()
136
+
137
+ # Exponential Moving Averages
138
+ df['EMA_20'] = df['Close'].ewm(span=20, adjust=False).mean()
139
+ df['EMA_50'] = df['Close'].ewm(span=50, adjust=False).mean()
140
+
141
+ # Relative Strength Index (RSI)
142
+ delta = df['Close'].diff(1)
143
+ gain = delta.where(delta > 0, 0)
144
+ loss = -delta.where(delta < 0, 0)
145
+ avg_gain = gain.rolling(window=14).mean()
146
+ avg_loss = loss.rolling(window=14).mean()
147
+ rs = avg_gain / avg_loss
148
+ df['RSI'] = 100 - (100 / (1 + rs))
149
+
150
+ # Moving Average Convergence Divergence (MACD)
151
+ df['MACD'] = df['Close'].ewm(span=12, adjust=False).mean() - df['Close'].ewm(span=26, adjust=False).mean()
152
+ df['MACD_Signal'] = df['MACD'].ewm(span=9, adjust=False).mean()
153
+
154
+ return df
155
+
156
+ # Analyze and store data for all companies
157
+ def analyze_nifty_50(companies, start_date, end_date):
158
+ result = {}
159
+ for company in companies:
160
+ df = fetch_stock_data(company+".NS", start_date, end_date)
161
+ if df.empty:
162
+ continue
163
+ df_analyzed = analyze_data(df)
164
+ df_analyzed = add_technical_indicators(df_analyzed)
165
+
166
+ result[company] = {
167
+ 'open_to_high_avg': df_analyzed['Open_to_High'].mean(),
168
+ 'open_to_low_avg': df_analyzed['Open_to_Low'].mean(),
169
+ 'open_to_close_avg': df_analyzed['Open_to_Close'].mean(),
170
+ 'average_volume': df_analyzed['Volume'].mean(),
171
+ 'historical_average_volume': df['Volume'].mean(),
172
+ 'SMA_20': df_analyzed['SMA_20'].iloc[-1],
173
+ 'SMA_50': df_analyzed['SMA_50'].iloc[-1],
174
+ 'EMA_20': df_analyzed['EMA_20'].iloc[-1],
175
+ 'EMA_50': df_analyzed['EMA_50'].iloc[-1],
176
+ 'RSI': df_analyzed['RSI'].iloc[-1],
177
+ 'MACD': df_analyzed['MACD'].iloc[-1],
178
+ 'MACD_Signal': df_analyzed['MACD_Signal'].iloc[-1]
179
+ }
180
+ return result
181
+
182
+
183
+ tabs = ["Fundamental Analysis", "Technical Analysis"]
184
+ tab = st.tabs(tabs)
185
+
186
+ with tab[0]:
187
+ # Fundamental Analysis
188
+ st.header("Fundamental Analysis")
189
+ st.info("If You Enter List of Companies Manually Not Mention '.NS' after Company Name")
190
+ fundamental_text_input = st.text_input("Enter List of Company Names",placeholder="Enter Comma Seperated List of Companies")
191
+ st.write("or")
192
+ st.write("Get Automatically Nifty 50 Companies, Click 'Run Fundamental Analysis'")
193
+ fundamental_button = st.button("Run Fundamental Analysis")
194
+ if fundamental_button:
195
+ # Fetch data for all Nifty 50 companies
196
+ if fundamental_text_input:
197
+ nifty_50_tickers = fundamental_text_input.split(",")
198
+ else:
199
+ nifty_50_tickers = ns.get_nifty50()
200
+ nifty_50_data = {ticker: get_financial_data(ticker+'.NS') for ticker in nifty_50_tickers}
201
+ details_of_companies = {}
202
+ for ticker, data in nifty_50_data.items():
203
+ details_of_companies[ticker] = summarize_company(ticker, data)
204
+
205
+ fundamental_df = pd.DataFrame(details_of_companies)
206
+ fundamental_df.drop('Company', inplace=True)
207
+ fundamental_df = fundamental_df.transpose()
208
+ fundamental_df.index.name = 'Company'
209
+ all_company_summary = ""
210
+ for ticker, data in details_of_companies.items():
211
+ all_company_summary += f"\n\n----{ticker}----"+"\n\n"+summarize_text_fundamental(data)
212
+ print(data)
213
+ fundamental_df.loc[ticker, 'summary'] = "\n\nCompany:"+ticker+"\n\n"+summarize_text_fundamental(data)
214
+ print(ticker)
215
+ summary_for_fundamental = ""
216
+ for i in range(len(all_company_summary.split("\n\n"))):
217
+ summary_for_fundamental += all_company_summary.split("\n\n")[i]+" \n\n"
218
+ # Display the results
219
+ st.write(fundamental_df)
220
+ st.download_button("Download CSV", fundamental_df.to_csv(), "nifty_50_fundamental_analysis.csv")
221
+ st.write(summary_for_fundamental)
222
+
223
+ with tab[1]:
224
+ # Technical Analysis
225
+ st.header("Technical Analysis")
226
+ st.info("If You Enter List of Companies Manually Not Mention '.NS' after Company Name")
227
+ st.info("If the Result 'difficult to make decision' it is may not good for invest.")
228
+ start_date = st.date_input("Start Date")
229
+ end_date = st.date_input("End Date")
230
+ technical_text_input = st.text_input("Enter List of Company Names ---",placeholder="Enter Comma Seperated List of Companies")
231
+ st.write("or")
232
+ st.write("Get Automatically Nifty 50 Companies, Click 'Run Technical Analysis'")
233
+ technical_button = st.button("Run Technical Analysis")
234
+ if technical_button:
235
+ # Analyze the data
236
+ if technical_text_input:
237
+ nifty_50_companies = technical_text_input.split(",")
238
+ else:
239
+ nifty_50_companies = ns.get_nifty50()
240
+ nifty_50_analysis = analyze_nifty_50(nifty_50_companies, start_date, end_date)
241
+ technical_df = pd.DataFrame(nifty_50_analysis)
242
+ technical_df = technical_df.transpose()
243
+ technical_df.index.name = 'Company'
244
+ all_company_summary = ""
245
+ for ticker, data in nifty_50_analysis.items():
246
+ print(data)
247
+ all_company_summary += f"\n\n----{ticker}----"+"\n\n"+summarize_text_technical(data)
248
+ technical_df.loc[ticker, 'summary'] = "\n\nCompany:"+ticker+"\n\n"+summarize_text_technical(data)
249
+
250
+ technical_df.to_csv("nifty_50_technical_analysis.csv")
251
+ summary_for_technical = ""
252
+
253
+ for i in range(len(all_company_summary.split("\n\n"))):
254
+ summary_for_technical +=all_company_summary.split("\n\n")[i]+" \n\n"
255
+
256
+ # Display the results
257
+ st.write(technical_df)
258
+ st.download_button("Download CSV", technical_df.to_csv(), "nifty_50_technical_analysis.csv")
259
+
260
+ st.write(summary_for_technical)