Files
strategy-lab/to_explore/pyquantnews/64_LangChainSentimentAnalysis.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

5.0 KiB

No description has been provided for this image

This code performs sentiment analysis on news articles related to Microsoft (MSFT) using a predefined language model. It imports necessary libraries, loads environment variables, and sets up a language chain model with a prompt template. The code then fetches news articles, applies the sentiment analysis model to each news description, and appends the sentiment results. Finally, it displays the news descriptions along with their corresponding sentiments.

In [ ]:
from openbb_terminal.sdk import openbb
In [ ]:
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.chat_models import ChatOpenAI
In [ ]:
from dotenv import load_dotenv
In [ ]:
load_dotenv()
In [ ]:
import pandas as pd
In [ ]:
pd.set_option("max_colwidth", None)

Initialize the language model with GPT-4 and set temperature for response variability

In [ ]:
llm = ChatOpenAI(model="gpt-4", temperature=0)

Define the sentiment analysis prompt template

In [ ]:
prompt = """
Is the predominant sentiment in the following statement positive, negative, or neutral?
---------
Statement: {statement}
---------
Respond with one word in lowercase: positive, negative, or neutral.
Sentiment:
"""

Create a sentiment analysis chain using the language model and prompt template

In [ ]:
chain = LLMChain.from_string(
    llm=llm,
    template=prompt
)

Fetch news articles related to Microsoft (MSFT) using the OpenBB SDK

In [ ]:
msft = openbb.news(term="msft")

Apply the sentiment analysis chain to each news description and add the sentiment results to a new column

In [ ]:
msft["Sentiment"] = msft.Description.apply(chain.run)

Display the news descriptions along with their corresponding sentiment results

In [ ]:
msft[["Description", "Sentiment"]]

PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.