SW/Python

FinBERT와 VaderSentiment를 이용한 정확한 시장 뉴스 감정 분석

얇은생각 2024. 2. 6. 07:30
반응형

금융 시장은 복잡하고 예측하기 어렵습니다. 투자자들의 감정과 시장의 뉴스는 주식 가격에 큰 영향을 미칩니다. 이런 맥락에서, 감정 분석은 주식 가격의 움직임을 예측하는 데 중요한 도구가 되었습니다. 최근 연구에서는 파이썬과 Jupyter Notebook을 활용하여 FinBERT VaderSentiment, 두 가지 주요 감정 분석 알고리즘을 비교 분석함으로써 더 정확한 시장 뉴스 감정 분석을 달성하는 방법을 탐구했습니다. 이 블로그 포스트에서는 해당 연구의 방법론과 결과, 그리고 코드의 구조를 개선하기 위해 적용된 SOLID 원칙에 대해 논의하겠습니다.

 

 

FinBERT와 VaderSentiment를 이용한 정확한 시장 뉴스 감정 분석

 

 

FinBERT VaderSentiment 감정 분석

감정 분석은 텍스트의 감정적 색채를 파악하여 긍정적, 중립적, 또는 부정적으로 분류하는 과정입니다. 이 연구에서는 두 가지 NLP(Natural Language Processing) 알고리즘, FinBERT VaderSentiment를 사용했습니다.

FinBERT는 금융 특화 모델로, 특히 금융 관련 텍스트에 대한 높은 정확도를 보입니다. 반면, VaderSentiment는 소셜 미디어 텍스트의 감정을 분석하는 데 널리 사용되며, 일반적인 언어에 대한 감정을 분석하는 데 효과적입니다.

 

 

연구 방법론 및 결과

Yahoo Finance API를 통해 시장 뉴스 데이터를 수집했고, 이 데이터는 Pandas 데이터프레임으로 변환되었습니다. 그 후, 데이터프레임의 'Headline' 열에 대해 FinBERT VaderSentiment 알고리즘을 적용하여 각각의 감정 점수를 계산했습니다. 이 점수들은 데이터프레임에 새로운 열로 추가되었고, 수동으로 비교 분석하여 FinBERT의 감정 점수가 더 정확하다는 결론을 내렸습니다.

 

 

SOLID 원칙 적용

이 연구는 단순히 알고리즘의 비교에 그치지 않고, 코드의 품질과 유지보수성을 높이기 위해 SOLID 원칙을 적극적으로 적용했습니다. SOLID 원칙은 객체 지향 프로그래밍과 소프트웨어 설계에서 중요한 5가지 원칙을 말합니다. 특히, 이 연구에서는 Single Responsibility Principle Open/Closed Principle을 적용하여, 각각의 기능이 독립적으로 존재하고 확장 가능하도록 구조를 재편했습니다.

 

 

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()

 

 

결론

시장 뉴스의 감정 분석 정확도를 향상시키는 것은 금융 시장에서 중요한 역할을 합니다. 이 연구를 통해 FinBERT VaderSentiment의 감정 분석 알고리즘을 비교하고, 더 나은 트레이딩 전략을 위해 정확도를 높이는 방법을 탐구했습니다. 또한, 코드의 구조를 개선하여 유지보수성과 확장성을 높이는 것의 중요성을 보여주었습니다. 이 연구는 금융 분석가, 데이터 과학자, 소프트웨어 개발자들에게 유용한 지침을 제공합니다.

반응형