Real-Time Stock Sentiment Analysis w/ NLP Web Scraping

Featured Image via Canva.

  • Recently, stock sentiment analysis has become a popular technique to gain insights into the public opinions of a specific asset.
  • The objective of this study is to extract stock sentiments from financial news headlines in the FinViz website using the NLP web scraping algorithm in Python.
  • An example of the news headlines section for Amazon from the FinViz website is given here.
  • Prerequisites: Pandas, BeautifulSoup, and NLTK.
  • Read more here.

FinViz Web Scraping

  • Let’s set the working directory, import the key libraries and define the stock ticker(s) of interest
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt

from bs4 import BeautifulSoup
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import requests


tickers_list = ['TSLA']
  • Reading the weekly stock news headlines
news = pd.DataFrame()

for ticker in tickers_list:
   url = f'https://finviz.com/quote.ashx?t={ticker}&p=d'
   ret = requests.get(
       url,
       headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'},
   )
   
   html = BeautifulSoup(ret.content, "html.parser")
   
   try:
     df = pd.read_html(
         str(html),
         attrs={'class': 'fullview-news-outer'}
     )[0]
   except:
     print(f"{ticker} No news found")
     continue
 
   df.columns = ['Date', 'Headline']

df.tail()
TSLA headlines
  • Processing date and time columns
dateNTime = df.Date.apply(lambda x: ','+x if len(x)<8 else x).str.split(r' |,', expand = True).replace("", None).ffill()
df = pd.merge(df, dateNTime, right_index=True, left_index=True).drop('Date', axis=1).rename(columns={0:'Date', 1:'Time'})
df = df[df["Headline"].str.contains("Loading.") == False].loc[:, ['Date', 'Time', 'Headline']]
df["Ticker"] = ticker
news = pd.concat([news, df], ignore_index = True)
news.head()
TSLA news vs date and time

NLP Sentiment Analysis

  • Downloading package vader_lexicon and applying vader.polarity_scores to news
nltk.download('vader_lexicon')
vader = SentimentIntensityAnalyzer()

scored_news = news.join(
  pd.DataFrame(news['Headline'].apply(vader.polarity_scores).tolist())
)

Stock Sentiment Scores

  • Plotting the TSLA news score (as of Dec-23-23)
news_score = scored_news.loc[:, ['Ticker', 'Date', 'compound']].pivot_table(values='compound', index='Date', columns='Ticker', aggfunc='mean').ewm(15).mean()
news_score.dropna().plot(figsize=(10, 6),linewidth=4,kind='line',legend=True, fontsize=14)
plt.title("Weekly Sentiment Score for TSLA",fontsize=14)
Weekly Sentiment Score for TSLA
  • Plotting the pct_change() of TSLA news score
news_score.pct_change().dropna().plot(figsize=(10, 6),linewidth=4,kind='line',legend=True, fontsize=14)
plt.title("Percentage Change of Weekly Sentiment Score for TSLA",fontsize=14)
Percentage Change of Weekly Sentiment Score for TSLA
  • Applying the algorithm to tickers_list = [‘NVDA’]
Weekly Sentiment Score for NVDA
Percentage Change of Weekly Sentiment Score for NVDA
  • Applying the algorithm to XOM (as of Dec-14-23)
Weekly Sentiment Score for XOM
Percentage Change of Weekly Sentiment Score for XOM

Conclusions

  • We have implemented the stock sentiment analysis that can be used to determine investors’ opinions of a specific asset. 
  • We have used the Python code to parse the FinViz website data and assign a sentiment score to each stock-related headline before averaging it over a period of time (e.g. 1 week).
  • Business value: the impact of negative sentiment could lead to an increase in traders looking to sell the share (i.e. the “bearish” sentiment); the opposite can also be true when positive news is released, which may boost the stock (i.e. the “bullish” sentiment). 
  • Bottom line: stock sentiment alone cannot always predict changes in share prices, but when combined with tools such as technical analysis, a better understanding can be gained to determine possible scenarios.

Explore More


Go back

Your message has been sent

Warning

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

€5.00
€15.00
€100.00
€5.00
€15.00
€100.00
€5.00
€15.00
€100.00

Or enter a custom amount


Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

Discover more from Our Blogs

Subscribe to get the latest posts sent to your email.

Leave a comment

Discover more from Our Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading