eshan6704 commited on
Commit
c14c75e
·
verified ·
1 Parent(s): bc71b9f

Create stock.py

Browse files
Files changed (1) hide show
  1. stock.py +420 -0
stock.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import yfinance as yf
3
+ import pandas as pd
4
+
5
+ def yfinfo(symbol):
6
+
7
+ tk = yf.Ticker(symbol + ".NS")
8
+ return tk.info
9
+
10
+ def qresult(symbol):
11
+
12
+ ticker = yf.Ticker(symbol + ".NS")
13
+ df = ticker.quarterly_financials
14
+ return df
15
+
16
+ def result(symbol):
17
+
18
+ ticker = yf.Ticker(symbol + ".NS")
19
+ df = ticker.financials
20
+ return df
21
+
22
+ def balance(symbol):
23
+
24
+ ticker = yf.Ticker(symbol + ".NS")
25
+ df = ticker.balance_sheet
26
+ return df
27
+
28
+ def cashflow(symbol):
29
+
30
+ ticker = yf.Ticker(symbol + ".NS")
31
+ df = ticker.cashflow
32
+ return df
33
+
34
+ def dividend(symbol):
35
+ ticker = yf.Ticker(symbol + ".NS")
36
+ df = ticker.dividends.to_frame('Dividend')
37
+ return df
38
+
39
+ def split(symbol):
40
+ ticker = yf.Ticker(symbol + ".NS")
41
+ df = ticker.splits.to_frame('Split')
42
+ return df
43
+
44
+ def intraday(symbol):
45
+
46
+ df = ticker.download(symbol + ".NS",period="1d",interval="5min").round(2)
47
+ return df
48
+
49
+ def daily(symbol):
50
+
51
+ df = ticker.download(symbol + ".NS",period="1y",interval="1d").round(2)
52
+ return df
53
+
54
+ # ============================
55
+ # info.py — Company Info Page
56
+ # EXACT SAME LOOK AS BEFORE
57
+ # ============================
58
+
59
+ import yfinance as yf
60
+ import pandas as pd
61
+ import traceback
62
+
63
+ from yf import yfinfo
64
+
65
+ from common import (format_number,format_large_number,make_table,html_card,html_section,html_error,clean_df,safe_get)
66
+
67
+
68
+ def fetch_info(symbol: str):
69
+ """
70
+ Fetch full company info and return the SAME layout you used earlier.
71
+ Only internal code updated to use common.py helpers.
72
+ """
73
+ try:
74
+
75
+ info = yfinfo(symbol)
76
+
77
+ if not info:
78
+ return html_error(f"No information found for {symbol}")
79
+
80
+ # ===== BASIC DETAILS =====
81
+ basic = {
82
+ "Symbol": symbol,
83
+ "Name": safe_get(info, "longName"),
84
+ "Sector": safe_get(info, "sector"),
85
+ "Industry": safe_get(info, "industry"),
86
+ "Website": safe_get(info, "website"),
87
+ "Employee Count": format_large_number(safe_get(info, "fullTimeEmployees")),
88
+ }
89
+ df_basic = pd.DataFrame(basic.items(), columns=["Field", "Value"])
90
+ basic_html = make_table(df_basic)
91
+
92
+ # ===== PRICE DETAILS =====
93
+ price_info = {
94
+ "Current Price": format_number(safe_get(info, "currentPrice")),
95
+ "Previous Close": format_number(safe_get(info, "previousClose")),
96
+ "Open": format_number(safe_get(info, "open")),
97
+ "Day High": format_number(safe_get(info, "dayHigh")),
98
+ "Day Low": format_number(safe_get(info, "dayLow")),
99
+ "52W High": format_number(safe_get(info, "fiftyTwoWeekHigh")),
100
+ "52W Low": format_number(safe_get(info, "fiftyTwoWeekLow")),
101
+ "Volume": format_large_number(safe_get(info, "volume")),
102
+ "Avg Volume": format_large_number(safe_get(info, "averageVolume")),
103
+ }
104
+ df_price = pd.DataFrame(price_info.items(), columns=["Field", "Value"])
105
+ price_html = make_table(df_price)
106
+
107
+ # ===== VALUATION METRICS =====
108
+ valuation = {
109
+ "Market Cap": format_large_number(safe_get(info, "marketCap")),
110
+ "PE Ratio": format_number(safe_get(info, "trailingPE")),
111
+ "EPS": format_number(safe_get(info, "trailingEps")),
112
+ "PB Ratio": format_number(safe_get(info, "priceToBook")),
113
+ "Dividend Yield": format_number(safe_get(info, "dividendYield")),
114
+ "ROE": format_number(safe_get(info, "returnOnEquity")),
115
+ "ROA": format_number(safe_get(info, "returnOnAssets")),
116
+ }
117
+ df_val = pd.DataFrame(valuation.items(), columns=["Field", "Value"])
118
+ val_html = make_table(df_val)
119
+
120
+ # ===== COMPANY EXTRA DETAILS =====
121
+ extra = {
122
+ "Beta": format_number(safe_get(info, "beta")),
123
+ "Revenue": format_large_number(safe_get(info, "totalRevenue")),
124
+ "Gross Margins": format_number(safe_get(info, "grossMargins")),
125
+ "Operating Margins": format_number(safe_get(info, "operatingMargins")),
126
+ "Profit Margins": format_number(safe_get(info, "profitMargins")),
127
+ "Book Value": format_number(safe_get(info, "bookValue")),
128
+ }
129
+ df_extra = pd.DataFrame(extra.items(), columns=["Field", "Value"])
130
+ extra_html = make_table(df_extra)
131
+
132
+ # ========================
133
+ # Final HTML (Same Layout)
134
+ # ========================
135
+ final_html = (
136
+ html_card("Basic Information", basic_html)
137
+ + html_card("Price Details", price_html)
138
+ + html_card("Valuation Metrics", val_html)
139
+ + html_card("Additional Company Data", extra_html)
140
+ )
141
+
142
+ return final_html
143
+
144
+ except Exception as e:
145
+ return html_error(f"INFO MODULE ERROR: {e}<br><pre>{traceback.format_exc()}</pre>")
146
+ # intraday.py
147
+ import yfinance as yf
148
+ import pandas as pd
149
+ from common import format_large_number, wrap_html, make_table
150
+ from chart_builder import build_chart
151
+ from yf import intraday
152
+ # ============================================================
153
+ # INTRADAY DATA PROCESSING
154
+ # ============================================================
155
+
156
+ def fetch_intraday(symbol, indicators=None):
157
+
158
+ try:
159
+ # Fetch 1-day intraday 5-min interval
160
+ df = intraday(symbol)
161
+ if df.empty:
162
+ return wrap_html(f"<h1>No intraday data available for {symbol}</h1>")
163
+
164
+ # Reset MultiIndex if exists
165
+ if isinstance(df.columns, pd.MultiIndex):
166
+ df.columns = df.columns.get_level_values(0)
167
+
168
+ # Build chart with indicators
169
+ chart_html = build_chart(df, indicators=indicators, volume=True)
170
+
171
+ # Format last 50 rows for table
172
+ table_html = make_table(df.tail(50))
173
+
174
+ # Wrap in full HTML
175
+ full_html = wrap_html(f"{chart_html}<h2>Recent Intraday Data (last 50 rows)</h2>{table_html}",
176
+ title=f"Intraday Data for {symbol}")
177
+ return full_html
178
+
179
+ except Exception as e:
180
+ return wrap_html(f"<h1>Error fetching intraday data for {symbol}</h1><p>{str(e)}</p>")
181
+
182
+ import yfinance as yf
183
+ import pandas as pd
184
+ import io
185
+ import requests
186
+ from nse import daily
187
+ from datetime import datetime, timedelta
188
+ from ta_indi_pat import talib_df # use the combined talib_df function
189
+ from common import html_card, wrap_html
190
+ def fetch_daily(symbol, source,max_rows=200):
191
+ """
192
+ Fetch daily OHLCV data, calculate TA-Lib indicators + patterns,
193
+ return a single scrollable HTML table.
194
+ """
195
+ try:
196
+ # --- Fetch daily data ---
197
+ df=daily(symbol,source)
198
+
199
+ # --- Limit rows for display ---
200
+ df_display = df.head(max_rows)
201
+
202
+ # --- Generate combined TA-Lib DataFrame ---
203
+ combined_df = talib_df(df_display)
204
+
205
+ # --- Convert to HTML table ---
206
+ table_html = combined_df.to_html(
207
+ classes="table table-striped table-bordered",
208
+ index=False
209
+ )
210
+
211
+ # --- Wrap in scrollable div ---
212
+ scrollable_html = f"""
213
+ <div style="overflow-x:auto; overflow-y:auto; max-height:600px; border:1px solid #ccc; padding:5px;">
214
+ {table_html}
215
+ </div>
216
+ """
217
+
218
+ # --- Wrap in card and full HTML ---
219
+ content = f"""
220
+ <h2>{symbol} - Daily Data (OHLCV + Indicators + Patterns)</h2>
221
+ {html_card("TA-Lib Data", scrollable_html)}
222
+ """
223
+
224
+ return wrap_html(content, title=f"{symbol} Daily Data")
225
+
226
+ except Exception as e:
227
+ return html_card("Error", str(e))
228
+ # qresult.py
229
+ import yfinance as yf
230
+ import pandas as pd
231
+ from common import make_table, wrap_html, format_large_number, html_error
232
+ from yf import qresult
233
+ def fetch_qresult(symbol):
234
+ """
235
+ Fetch quarterly financials for a stock symbol and return HTML
236
+ """
237
+
238
+ try:
239
+
240
+ df = qresult(symbol)
241
+
242
+ if df.empty:
243
+ return wrap_html(f"<h1>No quarterly results available for {symbol}</h1>")
244
+
245
+ # Format numeric columns
246
+ df_formatted = df.copy()
247
+ for col in df_formatted.columns:
248
+ df_formatted[col] = df_formatted[col].apply(
249
+ lambda x: format_large_number(x) if isinstance(x, (int, float)) else x
250
+ )
251
+
252
+ # Format index (dates)
253
+ df_formatted.index = [str(i.date()) if hasattr(i, "date") else str(i) for i in df_formatted.index]
254
+
255
+ # Convert to pretty HTML table
256
+ table_html = make_table(df_formatted)
257
+
258
+ # Wrap into full HTML page
259
+ return wrap_html(table_html, title=f"{symbol} - Quarterly Results")
260
+
261
+ except Exception as e:
262
+ return wrap_html(html_error(f"Failed to fetch quarterly results: {e}"))
263
+ # result.py
264
+ import yfinance as yf
265
+ from common import make_table, wrap_html, format_large_number, html_error
266
+ from yf import result
267
+ def fetch_result(symbol):
268
+
269
+ try:
270
+
271
+ df = result(symbol)
272
+
273
+ if df.empty:
274
+ return wrap_html(f"<h1>No annual results available for {symbol}</h1>")
275
+
276
+ # Format numeric columns
277
+ df_formatted = df.copy()
278
+ for col in df_formatted.columns:
279
+ df_formatted[col] = df_formatted[col].apply(
280
+ lambda x: format_large_number(x) if isinstance(x, (int, float)) else x
281
+ )
282
+
283
+ df_formatted.index = [str(i.date()) if hasattr(i, "date") else str(i) for i in df_formatted.index]
284
+ table_html = make_table(df_formatted)
285
+
286
+ return wrap_html(table_html, title=f"{symbol} - Annual Results")
287
+
288
+ except Exception as e:
289
+ return wrap_html(html_error(f"Failed to fetch annual results: {e}"))
290
+
291
+ # balance.py
292
+ import yfinance as yf
293
+ from common import make_table, wrap_html, format_large_number, html_error
294
+ from yf import balance
295
+ def fetch_balance(symbol):
296
+
297
+ try:
298
+ df = balance(symbol)
299
+
300
+ if df.empty:
301
+ return wrap_html(f"<h1>No balance sheet available for {symbol}</h1>")
302
+
303
+ df_formatted = df.copy()
304
+ for col in df_formatted.columns:
305
+ df_formatted[col] = df_formatted[col].apply(
306
+ lambda x: format_large_number(x) if isinstance(x, (int, float)) else x
307
+ )
308
+
309
+ df_formatted.index = [str(i.date()) if hasattr(i, "date") else str(i) for i in df_formatted.index]
310
+ table_html = make_table(df_formatted)
311
+
312
+ return wrap_html(table_html, title=f"{symbol} - Balance Sheet")
313
+
314
+ except Exception as e:
315
+ return wrap_html(html_error(f"Failed to fetch balance sheet: {e}"))
316
+ # cashflow.py
317
+ import yfinance as yf
318
+ from common import make_table, wrap_html, format_large_number, html_error
319
+ from yf import cashflow
320
+ def fetch_cashflow(symbol):
321
+
322
+ try:
323
+
324
+ df = cashflow(symbol)
325
+
326
+ if df.empty:
327
+ return wrap_html(f"<h1>No cash flow data available for {symbol}</h1>")
328
+
329
+ df_formatted = df.copy()
330
+ for col in df_formatted.columns:
331
+ df_formatted[col] = df_formatted[col].apply(
332
+ lambda x: format_large_number(x) if isinstance(x, (int, float)) else x
333
+ )
334
+
335
+ df_formatted.index = [str(i.date()) if hasattr(i, "date") else str(i) for i in df_formatted.index]
336
+ table_html = make_table(df_formatted)
337
+
338
+ return wrap_html(table_html, title=f"{symbol} - Cash Flow")
339
+
340
+ except Exception as e:
341
+ return wrap_html(html_error(f"Failed to fetch cash flow data: {e}"))
342
+
343
+ # dividend.py
344
+ import yfinance as yf
345
+ from common import make_table, wrap_html, format_large_number, html_error
346
+ from yf import dividend
347
+ def fetch_dividend(symbol):
348
+
349
+ try:
350
+
351
+ df = dividend(symbol)
352
+
353
+ if df.empty:
354
+ return wrap_html(f"<h1>No dividend history available for {symbol}</h1>")
355
+
356
+ df_formatted = df.copy()
357
+ for col in df_formatted.columns:
358
+ df_formatted[col] = df_formatted[col].apply(
359
+ lambda x: format_large_number(x) if isinstance(x, (int, float)) else x
360
+ )
361
+
362
+ df_formatted.index = [str(i.date()) if hasattr(i, "date") else str(i) for i in df_formatted.index]
363
+ table_html = make_table(df_formatted)
364
+
365
+ return wrap_html(table_html, title=f"{symbol} - Dividend History")
366
+
367
+ except Exception as e:
368
+ return wrap_html(html_error(f"Failed to fetch dividend history: {e}"))
369
+ # split.py
370
+ import yfinance as yf
371
+ from common import make_table, wrap_html, format_large_number, html_error
372
+ from yf import split
373
+ def fetch_split(symbol):
374
+
375
+ try:
376
+
377
+ df = split(symbol)
378
+
379
+ if df.empty:
380
+ return wrap_html(f"<h1>No split history available for {symbol}</h1>")
381
+
382
+ df_formatted = df.copy()
383
+ for col in df_formatted.columns:
384
+ df_formatted[col] = df_formatted[col].apply(
385
+ lambda x: format_large_number(x) if isinstance(x, (int, float)) else x
386
+ )
387
+
388
+ df_formatted.index = [str(i.date()) if hasattr(i, "date") else str(i) for i in df_formatted.index]
389
+ table_html = make_table(df_formatted)
390
+
391
+ return wrap_html(table_html, title=f"{symbol} - Split History")
392
+
393
+ except Exception as e:
394
+ return wrap_html(html_error(f"Failed to fetch split history: {e}"))
395
+ # other.py
396
+ import yfinance as yf
397
+ from common import make_table, wrap_html, format_large_number, html_error
398
+
399
+ def fetch_other(symbol):
400
+ yfsymbol = symbol + ".NS"
401
+ try:
402
+ ticker = yf.Ticker(yfsymbol)
403
+ df = ticker.earnings
404
+
405
+ if df.empty:
406
+ return wrap_html(f"<h1>No earnings data available for {symbol}</h1>")
407
+
408
+ df_formatted = df.copy()
409
+ for col in df_formatted.columns:
410
+ df_formatted[col] = df_formatted[col].apply(
411
+ lambda x: format_large_number(x) if isinstance(x, (int, float)) else x
412
+ )
413
+
414
+ df_formatted.index = [str(i) for i in df_formatted.index]
415
+ table_html = make_table(df_formatted)
416
+
417
+ return wrap_html(table_html, title=f"{symbol} - Earnings")
418
+
419
+ except Exception as e:
420
+ return wrap_html(html_error(f"Failed to fetch earnings data: {e}"))