rajat5ranjan commited on
Commit
755dd14
Β·
verified Β·
1 Parent(s): 6c5cfe6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -139
app.py CHANGED
@@ -66,13 +66,14 @@ if ticker_user!="":
66
  # Based on the context below
67
  # {context}, Summarize the stock based on Historical data based on fundamental, price, news, sentiment , any red flags and suggest rating of the Stock in a 1 to 10 Scale"""
68
 
69
- llm_prompt_template = """You are an expert Stock Market Trader specializing in stock market insights derived from fundamental analysis, analytical trends, profit-based evaluations, and detailed company financials. Using your expertise, please analyze the stock based on the provided context below.
 
70
 
71
  Context:
72
  {input_documents}
73
 
74
  Task:
75
- Summarize the stock based on its historical and current data.
76
  Evaluate the stock on the following parameters:
77
  1. Company Fundamentals: Assess the stock's intrinsic value, growth potential, and financial health.
78
  2. Current & Future Price Trends: Analyze historical price movements and current price trends.
@@ -237,148 +238,133 @@ if ticker_user!="":
237
  # st.subheader("πŸ” Indicators")
238
  # st.dataframe(analysis_summary.indicators, use_container_width=True)
239
 
240
- url = "https://api.chart-img.com/v2/tradingview/advanced-chart"
241
- api_key = "l0iUFRSeqC9z7nDPTd1hnafPh2RrdcEy6rl6tNqV"
242
- headers = {
243
- "x-api-key": api_key,
244
- "content-type": "application/json"
245
- }
246
- data = {
247
- "height": 400,
248
- "theme": "light",
249
- "interval": "1D",
250
- "session": "extended",
251
- "symbol": f"NSE:{ticker_user}"
252
- }
 
 
253
 
254
- response = requests.post(url, headers=headers, json=data)
 
 
 
 
 
 
 
255
 
256
- if response.status_code == 200:
257
- with open("chart_t1.jpg", "wb") as f:
258
- f.write(response.content)
259
- with col2:
260
- st.image("chart_t1.jpg", caption='')
261
 
262
- llm_prompt = PromptTemplate.from_template(llm_prompt_template)
 
263
 
264
- llm_chain = LLMChain(llm=llm,prompt=llm_prompt)
265
- stuff_chain = StuffDocumentsChain(llm_chain=llm_chain,document_variable_name="input_documents")
266
-
267
- # res = stuff_chain.invoke(docs)
268
- res = stuff_chain.invoke({"input_documents": docs})
269
- #create the humanmassage propmt templete with the image file
270
- # hmessage = HumanMessage(
271
- # content=[
272
- # {
273
- # "type": "text",
274
- # "text": "Based on the Image, suggest a BUY and SELL Strategy along with Risk based approach using Stop loss/Target price. PROVIDE THE DETAILS based on just the FACTS present and PROVIDE THE DETAILS IN an JSON Object",
275
- # },
276
- # {"type": "image_url", "image_url": "chart_t1.jpg"},
277
- # ]
278
- # )
279
- # message = llm_vis.invoke([hmessage])
280
-
281
- # st.write(message.content)
282
 
 
 
 
283
 
284
- try:
285
- raw_text = res["output_text"]
286
-
287
- # Remove markdown code block delimiters if present
288
- if raw_text.startswith("```json"):
289
- raw_text = raw_text[len("```json"):]
290
-
291
- if raw_text.endswith("```"):
292
- raw_text = raw_text[:-3]
293
-
294
- # Also strip leading/trailing whitespace/newlines
295
- raw_text = raw_text.strip()
296
 
297
 
298
- data = json.loads(raw_text)
299
- # data = res["output_text"]
300
- # Header Info
301
- st.markdown(f"### {data['stock_summary']['company_name']} ({data['stock_summary']['ticker']}) | {data['stock_summary']['exchange']}")
302
- st.markdown(f"**Description**: {data['stock_summary']['description']}")
303
-
304
- # === Row 1: Price and Market Cap ===
305
- row1 = st.columns(3)
306
- row1[0].metric("πŸ’° Current Price", data["stock_summary"]["current_price"])
307
- row1[1].metric("🏒 Market Cap", data["stock_summary"]["market_cap"])
308
- row1[2].metric("⭐ Rating", data["overall_rating"]["rating"])
309
-
310
- # === Row 2: Historical Performance ===
311
- st.subheader("πŸ“Š Historical Performance")
312
- perf_cols = st.columns(len(data["stock_summary"]["historical_performance"]))
313
- for i, (k, v) in enumerate(data["stock_summary"]["historical_performance"].items()):
314
- perf_cols[i].metric(k.replace("_", " ").title(), v)
315
-
316
- # === Row 3: Fundamentals ===
317
- st.subheader("πŸ“˜ Company Fundamentals")
318
- row3 = st.columns(4)
319
- metrics = data["evaluation_parameters"]["company_fundamentals"]["key_metrics"]
320
- row3[0].metric("P/E Ratio", metrics["pe_ratio"])
321
- row3[1].metric("EPS YoY", metrics["eps_growth_yoy"])
322
- row3[2].metric("Revenue YoY", metrics["revenue_growth_yoy"])
323
- row3[3].metric("Dividend Yield", metrics["dividend_yield"])
324
-
325
- row3b = st.columns(4)
326
- row3b[0].metric("Net Income YoY", metrics["net_income_growth_yoy"])
327
- row3b[1].metric("Volume", metrics["volume"])
328
- row3b[2].metric("Return on Capital", metrics["return_on_capital"])
329
- row3b[3].metric("Balance Sheet", metrics["balance_sheet"])
330
-
331
- st.info(data["evaluation_parameters"]["company_fundamentals"]["assessment"])
332
-
333
- # === Row 4: Trends and Technicals ===
334
- st.subheader("πŸ“ˆ Trends & Technical Analysis")
335
- row4 = st.columns(3)
336
- row4[0].markdown(f"**Historical Trends:** {data['evaluation_parameters']['current_and_future_price_trends']['historical_trends']}")
337
- row4[1].markdown(f"**Current Trends:** {data['evaluation_parameters']['current_and_future_price_trends']['current_trends']}")
338
- row4[2].markdown(f"**Technical Indicators:** {data['evaluation_parameters']['current_and_future_price_trends']['technical_indicators']}")
339
-
340
- st.success(data["evaluation_parameters"]["current_and_future_price_trends"]["assessment"])
341
- st.caption(f"πŸ“ Notes: {data['evaluation_parameters']['current_and_future_price_trends']['technical_analysis_notes']}")
342
-
343
- # === Row 5: Sentiment ===
344
- st.subheader("πŸ“° News & Sentiment")
345
- sentiment_cols = st.columns(2)
346
- with sentiment_cols[0]:
347
- st.success("πŸ‘ Positive Sentiment")
348
- for s in data["evaluation_parameters"]["news_and_sentiment"]["positive_sentiment"]:
349
- st.write(f"βœ… {s}")
350
- with sentiment_cols[1]:
351
- st.error("πŸ‘Ž Negative Sentiment")
352
- for s in data["evaluation_parameters"]["news_and_sentiment"]["negative_sentiment"]:
353
- st.write(f"❌ {s}")
354
- st.info(data["evaluation_parameters"]["news_and_sentiment"]["assessment"])
355
-
356
- # === Row 6: Red Flags ===
357
- st.subheader("🚩 Red Flags")
358
- red_flag_cols = st.columns(3)
359
- for i, flag in enumerate(data["evaluation_parameters"]["red_flags"]):
360
- red_flag_cols[i].warning(f"**{flag['flag']}**\n{flag['details']}")
361
-
362
- # === Row 7: Investment Advice ===
363
- st.subheader("πŸ’‘ Investment Advice")
364
- advice_cols = st.columns(3)
365
- advice = data["investment_advice"]
366
- advice_cols[0].markdown(f"**Next 1 Week**\n{advice['next_1_weeks_outlook']}")
367
- advice_cols[1].markdown(f"**Next 5 Weeks**\n{advice['next_5_weeks_outlook']}")
368
- advice_cols[2].markdown(f"**Next 10 Weeks**\n{advice['next_10_weeks_outlook']}")
369
-
370
- action_cols = st.columns(3)
371
- action_cols[0].success(f"**Buy:** {advice['price_action_suggestions']['buy']}")
372
- action_cols[1].info(f"**Hold:** {advice['price_action_suggestions']['hold']}")
373
- action_cols[2].error(f"**Sell:** {advice['price_action_suggestions']['sell']}")
374
-
375
- # === Footer ===
376
- st.markdown("---")
377
- st.caption("Generated by AI-powered financial analysis dashboard.")
378
- except json.JSONDecodeError as e:
379
- st.error(f"JSON decode error: {e}")
380
- st.write("Raw text was:")
381
- st.text(res["output_text"])
382
- else:
383
- st.warning(f"Failed to retrieve image. Status code: {response.status_code}")
384
- st.warning("Response:", response.text)
 
66
  # Based on the context below
67
  # {context}, Summarize the stock based on Historical data based on fundamental, price, news, sentiment , any red flags and suggest rating of the Stock in a 1 to 10 Scale"""
68
 
69
+ llm_prompt_template = """You are an expert Stock Market Trader specializing in stock market insights derived from fundamental analysis, analytical trends, profit-based evaluations, news indicators from different sites and detailed company financials.
70
+ Using your expertise, please analyze the stock based on the provided context below.
71
 
72
  Context:
73
  {input_documents}
74
 
75
  Task:
76
+ Summarize the stock based on its historical and current data. Keep it CONCISE & BRIEF.
77
  Evaluate the stock on the following parameters:
78
  1. Company Fundamentals: Assess the stock's intrinsic value, growth potential, and financial health.
79
  2. Current & Future Price Trends: Analyze historical price movements and current price trends.
 
238
  # st.subheader("πŸ” Indicators")
239
  # st.dataframe(analysis_summary.indicators, use_container_width=True)
240
 
241
+ # url = "https://api.chart-img.com/v2/tradingview/advanced-chart"
242
+ # api_key = "l0iUFRSeqC9z7nDPTd1hnafPh2RrdcEy6rl6tNqV"
243
+ # headers = {
244
+ # "x-api-key": api_key,
245
+ # "content-type": "application/json"
246
+ # }
247
+ # data = {
248
+ # "height": 400,
249
+ # "theme": "light",
250
+ # "interval": "1D",
251
+ # "session": "extended",
252
+ # "symbol": f"NSE:{ticker_user}"
253
+ # }
254
+
255
+ # response = requests.post(url, headers=headers, json=data)
256
 
257
+ # if response.status_code == 200:
258
+ # with open("chart_t1.jpg", "wb") as f:
259
+ # f.write(response.content)
260
+ # with col2:
261
+ # st.image("chart_t1.jpg", caption='')
262
+ # else:
263
+ # st.warning(f"Failed to retrieve image. Status code: {response.status_code}")
264
+ # st.warning("Response:", response.text)
265
 
266
+ llm_prompt = PromptTemplate.from_template(llm_prompt_template)
 
 
 
 
267
 
268
+ llm_chain = LLMChain(llm=llm,prompt=llm_prompt)
269
+ stuff_chain = StuffDocumentsChain(llm_chain=llm_chain,document_variable_name="input_documents")
270
 
271
+ # res = stuff_chain.invoke(docs)
272
+ res = stuff_chain.invoke({"input_documents": docs})
273
+ try:
274
+ raw_text = res["output_text"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
 
276
+ # Remove markdown code block delimiters if present
277
+ if raw_text.startswith("```json"):
278
+ raw_text = raw_text[len("```json"):]
279
 
280
+ if raw_text.endswith("```"):
281
+ raw_text = raw_text[:-3]
282
+
283
+ # Also strip leading/trailing whitespace/newlines
284
+ raw_text = raw_text.strip()
 
 
 
 
 
 
 
285
 
286
 
287
+ data = json.loads(raw_text)
288
+ # data = res["output_text"]
289
+ # Header Info
290
+ st.markdown(f"### {data['stock_summary']['company_name']} ({data['stock_summary']['ticker']}) | {data['stock_summary']['exchange']}")
291
+ st.markdown(f"**Description**: {data['stock_summary']['description']}")
292
+
293
+ # === Row 1: Price and Market Cap ===
294
+ row1 = st.columns(3)
295
+ row1[0].metric("πŸ’° Current Price", data["stock_summary"]["current_price"])
296
+ row1[1].metric("🏒 Market Cap", data["stock_summary"]["market_cap"])
297
+ row1[2].metric("⭐ Rating", data["overall_rating"]["rating"])
298
+
299
+ # === Row 2: Historical Performance ===
300
+ st.subheader("πŸ“Š Historical Performance")
301
+ perf_cols = st.columns(len(data["stock_summary"]["historical_performance"]))
302
+ for i, (k, v) in enumerate(data["stock_summary"]["historical_performance"].items()):
303
+ perf_cols[i].metric(k.replace("_", " ").title(), v)
304
+
305
+ # === Row 3: Fundamentals ===
306
+ st.subheader("πŸ“˜ Company Fundamentals")
307
+ row3 = st.columns(4)
308
+ metrics = data["evaluation_parameters"]["company_fundamentals"]["key_metrics"]
309
+ row3[0].metric("P/E Ratio", metrics["pe_ratio"])
310
+ row3[1].metric("EPS YoY", metrics["eps_growth_yoy"])
311
+ row3[2].metric("Revenue YoY", metrics["revenue_growth_yoy"])
312
+ row3[3].metric("Dividend Yield", metrics["dividend_yield"])
313
+
314
+ row3b = st.columns(4)
315
+ row3b[0].metric("Net Income YoY", metrics["net_income_growth_yoy"])
316
+ row3b[1].metric("Volume", metrics["volume"])
317
+ row3b[2].metric("Return on Capital", metrics["return_on_capital"])
318
+ row3b[3].metric("Balance Sheet", metrics["balance_sheet"])
319
+
320
+ st.info(data["evaluation_parameters"]["company_fundamentals"]["assessment"])
321
+
322
+ # === Row 4: Trends and Technicals ===
323
+ st.subheader("πŸ“ˆ Trends & Technical Analysis")
324
+ row4 = st.columns(3)
325
+ row4[0].markdown(f"**Historical Trends:** {data['evaluation_parameters']['current_and_future_price_trends']['historical_trends']}")
326
+ row4[1].markdown(f"**Current Trends:** {data['evaluation_parameters']['current_and_future_price_trends']['current_trends']}")
327
+ row4[2].markdown(f"**Technical Indicators:** {data['evaluation_parameters']['current_and_future_price_trends']['technical_indicators']}")
328
+
329
+ st.success(data["evaluation_parameters"]["current_and_future_price_trends"]["assessment"])
330
+ st.caption(f"πŸ“ Notes: {data['evaluation_parameters']['current_and_future_price_trends']['technical_analysis_notes']}")
331
+
332
+ # === Row 5: Sentiment ===
333
+ st.subheader("πŸ“° News & Sentiment")
334
+ sentiment_cols = st.columns(2)
335
+ with sentiment_cols[0]:
336
+ st.success("πŸ‘ Positive Sentiment")
337
+ for s in data["evaluation_parameters"]["news_and_sentiment"]["positive_sentiment"]:
338
+ st.write(f"βœ… {s}")
339
+ with sentiment_cols[1]:
340
+ st.error("πŸ‘Ž Negative Sentiment")
341
+ for s in data["evaluation_parameters"]["news_and_sentiment"]["negative_sentiment"]:
342
+ st.write(f"❌ {s}")
343
+ st.info(data["evaluation_parameters"]["news_and_sentiment"]["assessment"])
344
+
345
+ # === Row 6: Red Flags ===
346
+ st.subheader("🚩 Red Flags")
347
+ red_flag_cols = st.columns(3)
348
+ for i, flag in enumerate(data["evaluation_parameters"]["red_flags"]):
349
+ red_flag_cols[i].warning(f"**{flag['flag']}**\n{flag['details']}")
350
+
351
+ # === Row 7: Investment Advice ===
352
+ st.subheader("πŸ’‘ Investment Advice")
353
+ advice_cols = st.columns(3)
354
+ advice = data["investment_advice"]
355
+ advice_cols[0].markdown(f"**Next 1 Week**\n{advice['next_1_weeks_outlook']}")
356
+ advice_cols[1].markdown(f"**Next 5 Weeks**\n{advice['next_5_weeks_outlook']}")
357
+ advice_cols[2].markdown(f"**Next 10 Weeks**\n{advice['next_10_weeks_outlook']}")
358
+
359
+ action_cols = st.columns(3)
360
+ action_cols[0].success(f"**Buy:** {advice['price_action_suggestions']['buy']}")
361
+ action_cols[1].info(f"**Hold:** {advice['price_action_suggestions']['hold']}")
362
+ action_cols[2].error(f"**Sell:** {advice['price_action_suggestions']['sell']}")
363
+
364
+ # === Footer ===
365
+ st.markdown("---")
366
+ st.caption("Generated by AI-powered financial analysis dashboard.")
367
+ except json.JSONDecodeError as e:
368
+ st.error(f"JSON decode error: {e}")
369
+ st.write("Raw text was:")
370
+ st.text(res["output_text"])