DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Augmented Analytics With PySpark and Sentiment Analysis
  • AI Advancement for API and Microservices
  • Navigating the Complexities of Text Summarization With NLP
  • Norm of a One-Dimensional Tensor in Python Libraries

Trending

  • Enhancing Performance With Amazon Elasticache Redis: In-Depth Insights Into Cluster and Non-Cluster Modes
  • Understanding Kernel Monitoring in Windows and Linux
  • Automated Data Extraction Using ChatGPT AI: Benefits, Examples
  • Machine Learning: A Revolutionizing Force in Cybersecurity
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Improving Sentiment Score Accuracy With FinBERT and Embracing SOLID Principles

Improving Sentiment Score Accuracy With FinBERT and Embracing SOLID Principles

In this lab, I've improved market news sentiment analysis accuracy with a popular FinBERT ML algorithm using Python Jupyter Notebook.

By 
David Shilman user avatar
David Shilman
DZone Core CORE ·
Oct. 06, 23 · Tutorial
Like (3)
Save
Tweet
Share
4.7K Views

Join the DZone community and get the full member experience.

Join For Free

In a previous lab titled “Building News Sentiment and Stock Price Performance Analysis NLP Application With Python,” I briefly touched upon the concept of algorithmic trading using automated market news sentiment analysis and its correlation with stock price performance. Market movements, especially in the short term, are often influenced by investors’’ sentiment. One of the main components of sentiment analysis trading strategies is the algorithmic computation of a sentiment score from raw text and then incorporating the sentiment score into the trading strategy. The more accurate the sentiment score, the better the likelihood of algorithmic trading predicting potential stock price movements.

stock sentiment analysis

In that previous lab, I used the vaderSentiment library. This time, I’ve decided to explore another NLP contender, the FinBERT NLP algorithm, and compare it against Vader's sentiment score accuracy with the intent of improving trading strategy returns.

The primary data source remains unchanged. Leveraging the Yahoo Finance API available on RapidAPI Hub, I’ve sourced the news data for our sentiment analysis exercise.

I used a Python Jupyter Notebook as the development playground for this experiment. In my Jupyter notebook, I first call the API class that retrieves market data from Yahoo and converts the JSON response into a Pandas data frame. You can find this code in my previous lab or the GitHub repo. I then apply the Vader and FinBERT ML algorithms against the "Headline" column in the data frame to compute corresponding sentiment scores and add them in a new sentiment score column for each NLP ML algorithm.

sentiment scores

A manual comparison of these scores shows that the FinBERT ML algorithm is more accurate.

FinBERT ML algorithm

I have also introduced a significant code restructure by incorporating the following SOLID principles.

  • Single responsibility principle: Market news preparation logic has been consolidated into the API class
  • Open/closed principle: Both, Vader and FinBERT-specific logic reside in the subclasses of SentimentAnalysisBase

jupyter

Python
 
import plotly.express as px
import plotly.graph_objects as go


class SentimentAnalysisBase():

	def calc_sentiment_score(self):
      	pass
    
    def plot_sentiment(self) -> go.Figure:

        column = 'sentiment_score'

        df_plot = self.df.drop(
            self.df[self.df[f'{column}'] == 0].index)

        fig = px.bar(data_frame=df_plot, x=df_plot['Date Time'], y=f'{column}',
                     title=f"{self.symbol} Hourly Sentiment Scores")
        return fig


class FinbertSentiment (SentimentAnalysisBase):

    def __init__(self):

        self._sentiment_analysis = pipeline(
            "sentiment-analysis", model="ProsusAI/finbert")
        super().__init__()

    def calc_sentiment_score(self):

        self.df['sentiment'] = self.df['Headline'].apply(
            self._sentiment_analysis)
        self.df['sentiment_score'] = self.df['sentiment'].apply(
            lambda x: {x[0]['label'] == 'negative': -1, x[0]['label'] == 'positive': 1}.get(True, 0) * x[0]['score'])
        super().calc_sentiment_score()
        

class VaderSentiment (SentimentAnalysisBase):

    nltk.downloader.download('vader_lexicon')

    def __init__(self) -> None:

        self.vader = SentimentIntensityAnalyzer()
        super().__init__()

    def calc_sentiment_score(self):

        self.df['sentiment'] = self.df['Headline'].apply(
            self.vader.polarity_scores)
        self.df['sentiment_score'] = self.df['sentiment'].apply(
            lambda x: x['compound'])
        super().calc_sentiment_score()


I hope this article was worth your time. You can find the code in this GitHub repo.

Happy coding!!!

NLP Sentiment analysis Algorithm jupyter notebook Python (language)

Opinions expressed by DZone contributors are their own.

Related

  • Augmented Analytics With PySpark and Sentiment Analysis
  • AI Advancement for API and Microservices
  • Navigating the Complexities of Text Summarization With NLP
  • Norm of a One-Dimensional Tensor in Python Libraries

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: