akazmi commited on
Commit
8b9ea9a
·
verified ·
1 Parent(s): 59c55ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -77
app.py CHANGED
@@ -1,7 +1,8 @@
1
  import streamlit as st
2
- from transformers import pipeline
3
- from bs4 import BeautifulSoup
4
  import requests
 
 
 
5
 
6
  # Set up models
7
  ner_model = "Cassie-0121/fin-bert-finetuned-ner"
@@ -12,94 +13,82 @@ ner = pipeline("ner", model=ner_model)
12
  sentiment_analyzer = pipeline("sentiment-analysis", model=sentiment_model)
13
  text_generator = pipeline("text-generation", model=text_gen_model)
14
 
15
- # Function to scrape recent stock news
16
  def get_stock_news(stock_symbol):
17
- url = f"https://finance.yahoo.com/quote/{stock_symbol}/news?p={stock_symbol}"
18
- headers = {"User-Agent": "Mozilla/5.0"}
 
 
19
  response = requests.get(url, headers=headers)
20
- soup = BeautifulSoup(response.text, 'html.parser')
21
- articles = soup.find_all('h3', class_="Mb(5px)")
 
 
 
 
 
 
 
 
 
22
 
23
- news_list = []
24
- for article in articles[:5]: # Limit to the top 5 news articles
25
- headline = article.get_text()
26
- news_list.append(headline)
27
- return news_list
28
 
29
  # App title
30
  st.title("AI-Powered Financial Analysis App")
31
 
32
- # Sidebar with stock data examples
33
  st.sidebar.header("Stock Data & Analysis")
34
- examples = {
35
- "Apple Inc. (AAPL)": "AAPL",
36
- "Tesla Inc. (TSLA)": "TSLA",
37
- "Amazon.com Inc. (AMZN)": "AMZN",
38
- "Microsoft Corp. (MSFT)": "MSFT",
39
- "Alphabet Inc. (GOOGL)": "GOOGL",
40
- "Other": "" # Placeholder for custom input
41
- }
42
-
43
- selected_example = st.sidebar.selectbox("Select a stock symbol or choose 'Other' to enter custom text:", list(examples.keys()))
44
 
45
- # If "Other" is selected, provide an input box for custom text
46
- if selected_example == "Other":
47
- input_text = st.sidebar.text_area("Enter your own stock data for analysis:")
48
- stock_symbol = None
49
- else:
50
- stock_symbol = examples[selected_example]
51
- input_text = f"Latest news for {selected_example}"
52
 
53
- # Display selected or inputted text for review
54
- st.subheader("Stock Data & Analysis")
55
- st.write(input_text if input_text else "Please select a stock or enter custom text for analysis.")
56
 
57
- # Fetch and display news for the selected stock
58
- if stock_symbol:
59
- st.subheader("Latest Stock News")
60
- news_articles = get_stock_news(stock_symbol)
61
- for article in news_articles:
62
- st.write(f"- {article}")
63
 
64
- # Key Financial Entities extraction with filtering
65
- st.subheader("Extracted Key Financial Entities")
66
- if input_text:
67
- entities = ner(input_text)
68
- filtered_entities = [entity for entity in entities if entity['score'] > 0.7 and entity['word'].isalpha()] # Filter low-score and non-alphabetic tokens
69
- for entity in filtered_entities:
70
- st.write(f"Entity: {entity['word']}, Label: {entity.get('entity', 'N/A')}, Score: {entity['score']:.2f}")
71
 
72
- # Sentiment Analysis
73
- st.subheader("Sentiment Analysis")
74
- if input_text:
75
- sentiment = sentiment_analyzer(input_text)
76
- for result in sentiment:
77
- st.write(f"Sentiment: {result['label']}, Score: {result['score']:.2f}")
78
 
79
- # Investment Advice or Strategy Generation with better prompt handling
80
- st.subheader("Investment Advice or Strategy")
81
- if input_text:
82
- prompt = f"Provide a clear and concise investment strategy for {selected_example if selected_example != 'Other' else 'the selected stock'} based on recent news and financial performance. "
83
- advice = text_generator(prompt + input_text, max_length=80, num_return_sequences=1)
84
- st.write(advice[0]['generated_text'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  else:
86
- st.write("No investment advice generated. Please select a stock or enter custom text.")
87
-
88
- # Make the app visually more attractive
89
- st.markdown(
90
- """
91
- <style>
92
- .stApp {
93
- background-color: #F5F5F5;
94
- }
95
- .stSidebar {
96
- background-color: #333333;
97
- color: white;
98
- }
99
- </style>
100
- """,
101
- unsafe_allow_html=True
102
- )
103
 
104
- # Footer
105
- st.sidebar.write("Powered by Hugging Face and Streamlit")
 
1
  import streamlit as st
 
 
2
  import requests
3
+ from bs4 import BeautifulSoup
4
+ from transformers import pipeline
5
+ import yfinance as yf
6
 
7
  # Set up models
8
  ner_model = "Cassie-0121/fin-bert-finetuned-ner"
 
13
  sentiment_analyzer = pipeline("sentiment-analysis", model=sentiment_model)
14
  text_generator = pipeline("text-generation", model=text_gen_model)
15
 
16
+ # Function to fetch stock news using web scraping from Yahoo Finance
17
  def get_stock_news(stock_symbol):
18
+ url = f'https://finance.yahoo.com/quote/{stock_symbol}?p={stock_symbol}'
19
+ headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
20
+
21
+ # Send request and parse the page
22
  response = requests.get(url, headers=headers)
23
+ soup = BeautifulSoup(response.content, 'html.parser')
24
+
25
+ # Extracting news headlines (For Yahoo Finance, it's under the 'Recent News' section)
26
+ headlines = []
27
+ news_section = soup.find_all('li', {'class': 'js-stream-content'})
28
+ for news_item in news_section:
29
+ headline = news_item.find('h3')
30
+ if headline:
31
+ headlines.append(headline.get_text())
32
+
33
+ return headlines
34
 
35
+ # Function to fetch stock data using Yahoo Finance (yfinance library)
36
+ def get_stock_data(stock_symbol):
37
+ stock = yf.Ticker(stock_symbol)
38
+ stock_info = stock.history(period="1d") # Fetching the latest stock data (1-day)
39
+ return stock_info
40
 
41
  # App title
42
  st.title("AI-Powered Financial Analysis App")
43
 
44
+ # Sidebar for stock symbol input
45
  st.sidebar.header("Stock Data & Analysis")
46
+ stock_symbol = st.sidebar.text_input("Enter Stock Symbol (e.g., AAPL for Apple):", "AAPL")
 
 
 
 
 
 
 
 
 
47
 
48
+ # Fetch stock data and news
49
+ if stock_symbol:
50
+ st.sidebar.write(f"Fetching data for {stock_symbol}...")
 
 
 
 
51
 
52
+ # Fetch stock news
53
+ stock_news = get_stock_news(stock_symbol)
 
54
 
55
+ # Fetch stock data (latest price, volume, etc.)
56
+ stock_data = get_stock_data(stock_symbol)
57
+
58
+ # Display stock data
59
+ st.subheader(f"Latest Stock Data for {stock_symbol}")
60
+ st.write(stock_data)
61
 
62
+ # Display stock news
63
+ st.subheader(f"Latest News for {stock_symbol}")
64
+ for news in stock_news:
65
+ st.write(news)
 
 
 
66
 
67
+ # Text for analysis
68
+ input_text = ' '.join(stock_news) # Combine news for analysis
 
 
 
 
69
 
70
+ # Display extracted entities
71
+ st.subheader("Extracted Key Financial Entities")
72
+ if input_text:
73
+ entities = ner(input_text)
74
+ for entity in entities:
75
+ st.write(f"Entity: {entity['word']}, Label: {entity.get('entity', 'N/A')}, Score: {entity.get('score', 0.0):.2f}")
76
+
77
+ # Sentiment Analysis
78
+ st.subheader("Sentiment Analysis")
79
+ if input_text:
80
+ sentiment = sentiment_analyzer(input_text)
81
+ for result in sentiment:
82
+ st.write(f"Sentiment: {result['label']}, Score: {result['score']:.2f}")
83
+
84
+ # Investment Advice or Strategy
85
+ st.subheader("Investment Advice or Strategy")
86
+ if input_text:
87
+ prompt = f"Provide a focused and complete investment strategy for {stock_symbol} based on the latest news and trends."
88
+ advice = text_generator(prompt + input_text, max_length=100, num_return_sequences=1, do_sample=True, temperature=0.7)
89
+ st.write(advice[0]['generated_text'])
90
  else:
91
+ st.write("Please enter a valid stock symbol to get analysis.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
+ # Optional: Footer for extra branding
94
+ st.sidebar.write("Powered by Hugging Face, Streamlit, and Web Scraping")