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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import requests
|
| 3 |
+
from bs4 import BeautifulSoup
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
import re
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import nltk
|
| 9 |
+
from nltk.sentiment.vader import SentimentIntensityAnalyzer
|
| 10 |
+
|
| 11 |
+
nltk.download('vader_lexicon')
|
| 12 |
+
|
| 13 |
+
st.set_page_config(page_title = "Daily News with Sentiment Analysis", layout = "wide")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# Streamlit App
|
| 17 |
+
#st.title('Daily News with Sentiment Analysis')
|
| 18 |
+
|
| 19 |
+
st.write("""
|
| 20 |
+
### How to Use This App
|
| 21 |
+
1. **Enter Stock Ticker**: Type the stock ticker symbol (e.g., 'AAPL' for Apple Inc.) in the sidebar.
|
| 22 |
+
2. **Get News**: Click the 'Get News' button to fetch the latest news articles related to the entered stock ticker.
|
| 23 |
+
3. **View News and Sentiment**: The app will display the news articles along with sentiment scores. Sentiment scores range from -1 (very negative) to 1 (very positive).
|
| 24 |
+
4. **Sort Data**: Feel free to sort data by any column as needed.
|
| 25 |
+
5. **Download Data**: Optionally, you can download the news data with sentiment analysis as a CSV file.
|
| 26 |
+
""")
|
| 27 |
+
|
| 28 |
+
# Sidebar inputs
|
| 29 |
+
st.sidebar.header('Input Parameters')
|
| 30 |
+
ticker = st.sidebar.text_input('Enter Stock Ticker', 'AAPL')
|
| 31 |
+
|
| 32 |
+
def get_finviz_news_raw(ticker):
|
| 33 |
+
finviz_url = f'https://finviz.com/quote.ashx?t={ticker}'
|
| 34 |
+
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0'}
|
| 35 |
+
response = requests.get(finviz_url, headers=headers)
|
| 36 |
+
|
| 37 |
+
if response.status_code != 200:
|
| 38 |
+
st.error(f"Error fetching data for {ticker}")
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
| 42 |
+
news_table = soup.find("table", class_="fullview-news-outer")
|
| 43 |
+
|
| 44 |
+
if not news_table:
|
| 45 |
+
st.error(f"No news found for {ticker}")
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
nltk.download('vader_lexicon')
|
| 50 |
+
|
| 51 |
+
# Function to get news from Finviz
|
| 52 |
+
def get_finviz_news_raw(ticker):
|
| 53 |
+
finviz_url = f'https://finviz.com/quote.ashx?t={ticker}'
|
| 54 |
+
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0'}
|
| 55 |
+
response = requests.get(finviz_url, headers=headers)
|
| 56 |
+
|
| 57 |
+
if response.status_code != 200:
|
| 58 |
+
st.error(f"Error fetching data for {ticker}")
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
| 62 |
+
news_table = soup.find("table", class_="fullview-news-outer")
|
| 63 |
+
|
| 64 |
+
if not news_table:
|
| 65 |
+
st.error(f"No news found for {ticker}")
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
news_rows = news_table.find_all("tr")
|
| 69 |
+
raw_data = []
|
| 70 |
+
|
| 71 |
+
for row in news_rows:
|
| 72 |
+
date_time_cell = row.find("td", align="right")
|
| 73 |
+
news_source_cell = row.find("td", class_="news-link-right")
|
| 74 |
+
news_title_cell = row.find("a", class_="tab-link-news")
|
| 75 |
+
|
| 76 |
+
date_time_str = date_time_cell.get_text().strip() if date_time_cell else ''
|
| 77 |
+
#news_source = news_source_cell.get_text().strip("()") if news_source_cell else ''
|
| 78 |
+
#news_source = news_source_cell.get_text().replace('(', '').replace(')', '') if news_source_cell else ''
|
| 79 |
+
news_source = news_source_cell.get_text() if news_source_cell else ''
|
| 80 |
+
|
| 81 |
+
news_title = news_title_cell.get_text().strip() if news_title_cell else ''
|
| 82 |
+
news_link = news_title_cell['href'] if news_title_cell else ''
|
| 83 |
+
|
| 84 |
+
raw_data.append({
|
| 85 |
+
"Datetime": date_time_str,
|
| 86 |
+
"Source": news_source,
|
| 87 |
+
"Title": news_title,
|
| 88 |
+
"Link": news_link
|
| 89 |
+
})
|
| 90 |
+
|
| 91 |
+
df = pd.DataFrame(raw_data)
|
| 92 |
+
return df
|
| 93 |
+
|
| 94 |
+
# Preprocess text for sentiment analysis
|
| 95 |
+
def preprocess_text(text):
|
| 96 |
+
text = re.sub(r'<.*?>', '', text) # Remove HTML tags
|
| 97 |
+
text = re.sub(r'[^a-zA-Z\s]', '', text) # Remove special characters and digits
|
| 98 |
+
text = re.sub(r'\s+', ' ', text).strip() # Remove extra spaces
|
| 99 |
+
return text
|
| 100 |
+
|
| 101 |
+
# Analyze sentiment using VADER
|
| 102 |
+
def analyze_sentiment(text):
|
| 103 |
+
sia = SentimentIntensityAnalyzer()
|
| 104 |
+
sentiment = sia.polarity_scores(text)
|
| 105 |
+
return sentiment['compound'] # Sentiment score between -1 (negative) and 1 (positive)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# Fetch and display news when the button is pressed
|
| 109 |
+
if st.sidebar.button('Get News'):
|
| 110 |
+
news_df_raw = get_finviz_news_raw(ticker)
|
| 111 |
+
|
| 112 |
+
if news_df_raw is not None and not news_df_raw.empty:
|
| 113 |
+
df = news_df_raw.copy()
|
| 114 |
+
|
| 115 |
+
# Get today's date
|
| 116 |
+
today_date = datetime.today().strftime('%Y-%m-%d')
|
| 117 |
+
|
| 118 |
+
# Initialize the date variable
|
| 119 |
+
current_date = None
|
| 120 |
+
|
| 121 |
+
# Lists to store the new column values
|
| 122 |
+
dates = []
|
| 123 |
+
times = []
|
| 124 |
+
|
| 125 |
+
# Process each row in the dataframe
|
| 126 |
+
for index, row in df.iterrows():
|
| 127 |
+
datetime_value = row['Datetime']
|
| 128 |
+
|
| 129 |
+
# Replace 'Today' with today's date
|
| 130 |
+
if 'Today' in datetime_value:
|
| 131 |
+
datetime_value = datetime_value.replace('Today', today_date)
|
| 132 |
+
|
| 133 |
+
# Check if the datetime_value contains a date
|
| 134 |
+
if ' ' in datetime_value and not datetime_value.split(' ')[0].isdigit():
|
| 135 |
+
# Extract date and time
|
| 136 |
+
current_date = datetime_value.split(' ')[0]
|
| 137 |
+
time_value = ' '.join(datetime_value.split(' ')[1:])
|
| 138 |
+
else:
|
| 139 |
+
# Only time is provided
|
| 140 |
+
time_value = datetime_value
|
| 141 |
+
|
| 142 |
+
# Add the current date and time to the lists
|
| 143 |
+
dates.append(current_date)
|
| 144 |
+
times.append(time_value)
|
| 145 |
+
|
| 146 |
+
# Add the new columns to the dataframe
|
| 147 |
+
df['Date'] = dates
|
| 148 |
+
df['Time'] = times
|
| 149 |
+
|
| 150 |
+
# Add Sentiment and Relevance
|
| 151 |
+
df['Cleaned_Title'] = df['Title'].apply(preprocess_text)
|
| 152 |
+
df['Sentiment'] = df['Cleaned_Title'].apply(analyze_sentiment)
|
| 153 |
+
|
| 154 |
+
# Remove Cleaned_Title column
|
| 155 |
+
df.drop(columns=['Cleaned_Title', 'Datetime', 'Source'], inplace=True)
|
| 156 |
+
df = df.reset_index(drop=True)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
st.write(f"## News for {ticker}")
|
| 160 |
+
#st.dataframe(df, height=600, width=1000) # Use st.dataframe with height and width to allow for resizing and better display
|
| 161 |
+
#st.table(df)
|
| 162 |
+
|
| 163 |
+
# Option to download data as CSV
|
| 164 |
+
csv = df.to_csv(index=False).encode('utf-8')
|
| 165 |
+
st.download_button(
|
| 166 |
+
label="Download data as CSV",
|
| 167 |
+
data=csv,
|
| 168 |
+
file_name=f'{ticker}_news_sentiment.csv',
|
| 169 |
+
mime='text/csv',
|
| 170 |
+
)
|
| 171 |
+
st.table(df)
|
| 172 |
+
else:
|
| 173 |
+
st.write(f"No news found for {ticker}")
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
hide_streamlit_style = """
|
| 177 |
+
<style>
|
| 178 |
+
#MainMenu {visibility: hidden;}
|
| 179 |
+
footer {visibility: hidden;}
|
| 180 |
+
</style>
|
| 181 |
+
"""
|
| 182 |
+
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|