rajat5ranjan commited on
Commit
5e3a022
·
verified ·
1 Parent(s): b07dea6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -89
app.py CHANGED
@@ -452,104 +452,108 @@ if activities == "Symbol Analysis":
452
  st.write("Raw text was:")
453
  st.text(res["output_text"])
454
  elif activities=="News Sentiment":
455
- url1 = f"https://economictimes.indiatimes.com/markets/stocks/news"
456
- url2 = f"https://www.livemint.com/market/stock-market-news/"
457
- url3 = f"https://in.tradingview.com/ideas/editors-picks/?type=trade"
458
- url4 = f"https://pulse.zerodha.com/"
459
- url5 = "https://upstox.com/news/market-news/stocks/"
460
- # url6 = "https://trendlyne.com/market-insights/"
461
 
462
- loader = WebBaseLoader([url1,
463
- url2,
464
- url3,
465
- url4,
466
- url5,
467
- # url6
468
- ])
469
- docs = loader.load()
470
- # st.write(docs)
471
- st.divider()
472
-
473
- 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.
474
- You will receive stock market news articles or stocks in news from various news websites which have India stock news feed. For the below context/input_documents, perform the following tasks:
475
-
476
- Context:
477
- {input_documents}
478
 
479
- 1. **Top picks**: After analyzing all provided data, rank the top 5-10 stocks to look at this week, including tickers, current sentiment, and why they made the list.
480
- 2. **Identify the stock(s)** mentioned (by ticker and company name).
481
- 3. **Sentiment analysis**: classify as Bullish, Bearish, or Neutral.
482
- 4. **Extract critical news**: What is the main event or update? (e.g., earnings beat, regulatory approval, management change, major contract or macro impact).
483
- 5. **Summarize impact**: Briefly explain how this news might affect stock price and investor behavior (e.g., “could boost investor confidence”, “sign indicates profit pressure”, etc.).
484
- 6. **Actionable signal**: Based on the sentiment and news, suggest whether this is a “Buy”, “Sell”, “Hold”, or “Watch” recommendation, and the rationale.
485
-
486
- PROVIDE THE DETAILS based on just the FACTS present in the document. Do NOT DUPLICATE the Output & hallucinate.
487
- ***Format your output as JSON*** with the following structure:
488
 
489
- ```json
490
- {{
491
- "top_picks": [
492
- {{
493
- "ticker": "TICKER",
494
- "company": "Company Name",
495
- "sentiment": "Bullish|Bearish|Neutral",
496
- "critical_news": "Brief summary of the key event",
497
- "impact_summary": "How this may affect the stock",
498
- "action": "Buy|Sell|Hold|Watch",
499
- "reason": "Why this stock ranks among top picks"
500
- }},
501
- ...
502
- ]
503
- }}
504
-
505
- """
506
-
507
-
508
- google_docs = get_google_news_documents("Indian Stock market news NSE, Stocks in Action, Stocks in News, Stocks to Buy in next few weeks", max_articles=10)
509
- docs.extend(google_docs)
510
- # st.write(docs)
511
- llm_prompt = PromptTemplate.from_template(llm_prompt_template)
512
-
513
- llm_chain = LLMChain(llm=llm,prompt=llm_prompt)
514
- stuff_chain = StuffDocumentsChain(llm_chain=llm_chain,document_variable_name="input_documents")
515
 
516
- # res = stuff_chain.invoke(docs)
517
- res = stuff_chain.invoke({"input_documents": docs})
518
- raw_text = res["output_text"]
519
- # Remove markdown code block delimiters if present
520
- if raw_text.startswith("```json"):
521
- raw_text = raw_text[len("```json"):]
522
 
523
- if raw_text.endswith("```"):
524
- raw_text = raw_text[:-3]
525
 
526
- # Also strip leading/trailing whitespace/newlines
527
- raw_text = raw_text.strip()
528
-
529
- # Parse JSON
530
- parsed_data = json.loads(raw_text)
531
- top_picks = parsed_data.get("top_picks", [])
532
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
533
 
534
- # Layout
535
- for stock in top_picks:
536
- st.subheader(f"{stock['company']} ({stock['ticker']})")
537
- col1,col2,col3, col4 = st.columns([1,1,1, 1])
538
- with col1:
539
- st.markdown(f"**📰 Critical News:** {stock['critical_news']}")
540
- with col2:
541
- st.markdown(f"**📈 Impact Summary:** {stock['impact_summary']}")
542
- with col3:
543
- st.markdown(f"**💡 Reason for Top Pick:** {stock['reason']}")
544
- with col4:
545
- sentiment_color = {
546
- "Bullish": "🟢 Bullish",
547
- "Bearish": "🔴 Bearish",
548
- "Neutral": "🟡 Neutral"
549
- }.get(stock["sentiment"], stock["sentiment"])
550
- st.metric(label="Sentiment", value=sentiment_color)
551
- st.markdown(f"**🚦 Action:** :red[{stock['action']}]")
552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
553
  st.divider()
554
 
555
 
 
452
  st.write("Raw text was:")
453
  st.text(res["output_text"])
454
  elif activities=="News Sentiment":
 
 
 
 
 
 
455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456
 
457
+ if st.button("Get Live Updates..."):
458
+ url1 = f"https://economictimes.indiatimes.com/markets/stocks/news"
459
+ url2 = f"https://www.livemint.com/market/stock-market-news/"
460
+ url3 = f"https://in.tradingview.com/ideas/editors-picks/?type=trade"
461
+ url4 = f"https://pulse.zerodha.com/"
462
+ url5 = "https://upstox.com/news/market-news/stocks/"
463
+ # url6 = "https://trendlyne.com/market-insights/"
 
 
464
 
465
+ loader = WebBaseLoader([url1,
466
+ url2,
467
+ url3,
468
+ url4,
469
+ url5,
470
+ # url6
471
+ ])
472
+ docs = loader.load()
473
+ # st.write(docs)
474
+ st.divider()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
 
476
+ 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.
477
+ You will receive stock market news articles or stocks in news from various news websites which have India stock news feed. For the below context/input_documents, perform the following tasks:
 
 
 
 
478
 
479
+ Context:
480
+ {input_documents}
481
 
482
+ 1. **Top picks**: After analyzing all provided data, rank the top 5-10 stocks to look at this week, including tickers, current sentiment, and why they made the list.
483
+ 2. **Identify the stock(s)** mentioned (by ticker and company name).
484
+ 3. **Sentiment analysis**: classify as Bullish, Bearish, or Neutral.
485
+ 4. **Extract critical news**: What is the main event or update? (e.g., earnings beat, regulatory approval, management change, major contract or macro impact).
486
+ 5. **Summarize impact**: Briefly explain how this news might affect stock price and investor behavior (e.g., “could boost investor confidence”, “sign indicates profit pressure”, etc.).
487
+ 6. **Actionable signal**: Based on the sentiment and news, suggest whether this is a “Buy”, “Sell”, “Hold”, or “Watch” recommendation, and the rationale.
488
 
489
+ PROVIDE THE DETAILS based on just the FACTS present in the document. Do NOT DUPLICATE the Output & hallucinate.
490
+ ***Format your output as JSON*** with the following structure:
491
+
492
+ ```json
493
+ {{
494
+ "top_picks": [
495
+ {{
496
+ "ticker": "TICKER",
497
+ "company": "Company Name",
498
+ "sentiment": "Bullish|Bearish|Neutral",
499
+ "critical_news": "Brief summary of the key event",
500
+ "impact_summary": "How this may affect the stock",
501
+ "action": "Buy|Sell|Hold|Watch",
502
+ "reason": "Why this stock ranks among top picks"
503
+ }},
504
+ ...
505
+ ]
506
+ }}
507
 
508
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509
 
510
+
511
+ google_docs = get_google_news_documents("Indian Stock market news NSE, Stocks in Action, Stocks in News, Stocks to Buy in next few weeks", max_articles=10)
512
+ docs.extend(google_docs)
513
+ # st.write(docs)
514
+ llm_prompt = PromptTemplate.from_template(llm_prompt_template)
515
+
516
+ llm_chain = LLMChain(llm=llm,prompt=llm_prompt)
517
+ stuff_chain = StuffDocumentsChain(llm_chain=llm_chain,document_variable_name="input_documents")
518
+
519
+ # res = stuff_chain.invoke(docs)
520
+ res = stuff_chain.invoke({"input_documents": docs})
521
+ raw_text = res["output_text"]
522
+ # Remove markdown code block delimiters if present
523
+ if raw_text.startswith("```json"):
524
+ raw_text = raw_text[len("```json"):]
525
+
526
+ if raw_text.endswith("```"):
527
+ raw_text = raw_text[:-3]
528
+
529
+ # Also strip leading/trailing whitespace/newlines
530
+ raw_text = raw_text.strip()
531
+
532
+ # Parse JSON
533
+ parsed_data = json.loads(raw_text)
534
+ top_picks = parsed_data.get("top_picks", [])
535
+
536
+
537
+ # Layout
538
+ for stock in top_picks:
539
+ st.subheader(f"{stock['company']} ({stock['ticker']})")
540
+ col1,col2,col3, col4 = st.columns([1,1,1, 1])
541
+ with col1:
542
+ st.markdown(f"**📰 Critical News:** {stock['critical_news']}")
543
+ with col2:
544
+ st.markdown(f"**📈 Impact Summary:** {stock['impact_summary']}")
545
+ with col3:
546
+ st.markdown(f"**💡 Reason for Top Pick:** {stock['reason']}")
547
+ with col4:
548
+ sentiment_color = {
549
+ "Bullish": "🟢 Bullish",
550
+ "Bearish": "🔴 Bearish",
551
+ "Neutral": "🟡 Neutral"
552
+ }.get(stock["sentiment"], stock["sentiment"])
553
+ st.metric(label="Sentiment", value=sentiment_color)
554
+ st.markdown(f"**🚦 Action:** :red[{stock['action']}]")
555
+ else:
556
+ pass
557
  st.divider()
558
 
559