Building a Personalized Investment Research Automation Dashboard with NewsAPI, Llama 3, and Streamlit: News Sentiment Analysis, Company Performance Prediction, Portfolio Recommendation
Individual investors often struggle to efficiently analyze vast news data and complex financial information to make informed investment decisions. This article explains how to build an automated investment research dashboard that combines NewsAPI, Llama 3, and Streamlit to provide news sentiment analysis, company performance prediction, and personalized portfolio recommendations. This can revolutionize the investment research process and help achieve better investment outcomes.
1. The Challenge / Context
Individual investors face information overload. It is almost impossible to manually analyze the vast amount of data, including daily news articles, company reports, and economic indicators. Traditional investment research methods are time-consuming, susceptible to subjective bias, and often lack sufficient information. Especially, an automated data analysis and decision support system is essential to respond quickly to rapidly changing market conditions.
2. Deep Dive: Llama 3
Llama 3 is a state-of-the-art large language model (LLM) developed by Meta. It offers significantly more powerful reasoning capabilities, contextual understanding, and code generation abilities than its predecessors. In particular, Llama 3 is highly useful for analyzing financial news and reports, performing sentiment analysis, and predicting company performance. Because Llama 3 has been trained on an extensive dataset, it can provide accurate and reliable results based on a deep understanding of financial markets. Key features include:
- Enhanced Reasoning Capability: Better understands complex financial concepts and relationships, and performs logical reasoning.
- Accurate Sentiment Analysis: Accurately identifies positive, negative, and neutral sentiments in news articles and social media posts.
- Code Generation and Execution: Automatically generates and executes Python code for data analysis and visualization.
- Continuous Learning and Improvement: Continuously learns and improves through new data and feedback.
3. Step-by-Step Guide / Implementation
Now, let's look at the step-by-step process of building a personalized investment research automation dashboard using NewsAPI, Llama 3, and Streamlit.
Step 1: NewsAPI Setup and News Data Collection
NewsAPI provides a simple API to access thousands of news sources worldwide. First, you need to create a NewsAPI account and obtain an API key.
import requests
NEWSAPI_KEY = "YOUR_NEWSAPI_KEY" # 여기에 발급받은 API 키를 입력하세요.
def get_news(query, num_articles=10):
url = f"https://newsapi.org/v2/everything?q={query}&apiKey={NEWSAPI_KEY}&pageSize={num_articles}"
response = requests.get(url)
data = response.json()
articles = data['articles']
return articles
# 예시: "삼성전자" 관련 뉴스 10개 가져오기
news = get_news("삼성전자", 10)
for article in news:
print(article['title'])
Step 2: News Sentiment Analysis using Llama 3
Input the collected news articles into Llama 3 to analyze the sentiment of each article. You can access Llama 3 via the OpenAI API or Meta's API.
import openai
import os
# OpenAI API 키 설정 (환경 변수에서 가져오거나 직접 입력)
openai.api_key = os.getenv("OPENAI_API_KEY") # 권장: 환경 변수 사용
def analyze_sentiment(text):
prompt = f"이 텍스트의 감성을 긍정적, 부정적, 중립적 중 하나로 분류하고, 그 이유를 간단하게 설명해주세요:\n\n{text}\n\n감성:"
try:
response = openai.Completion.create(
engine="text-davinci-003", # 적절한 모델 선택
prompt=prompt,
max_tokens=50,
n=1,
stop=None,
temperature=0.5,
)
sentiment = response.choices[0].text.strip()
return sentiment
except Exception as e:
print(f"Error analyzing sentiment: {e}")
return "Error"
# 예시: 뉴스 기사 감성 분석
if news:
sample_article = news[0]['description'] # description 필드 사용
sentiment = analyze_sentiment(sample_article)
print(f"감성 분석 결과: {sentiment}")
Caution: Using the Llama 3 (or other LLM) API may incur costs. Fees are charged based on usage, so manage your API key securely and minimize unnecessary calls.
Tip: You can improve the accuracy of sentiment analysis through Llama 3's prompt engineering. For example, you can clearly define the criteria for sentiment classification or define the sentiment for specific financial terms.
Step 3: Building a Company Performance Prediction Model (Optional)
You can build a model to predict company performance using historical stock price data, financial statement data, and news sentiment analysis results. This step requires advanced analytical skills and can utilize various machine learning algorithms. Here, we use the Prophet library as a simple example.
# Prophet 라이브러리를 이용한 시계열 예측 (예시)
from prophet import Prophet
import pandas as pd
# 예시 데이터: 날짜별 주가 데이터
data = {'ds': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'],
'y': [100, 101, 103, 102, 105]} # 'y'는 주가
df = pd.DataFrame(data)
df['ds'] = pd.to_datetime(df['ds'])
# Prophet 모델 초기화 및 학습
model = Prophet()
model.fit(df)
# 미래 3일 예측
future = model.make_future_dataframe(periods=3)
forecast = model.predict(future)
# 예측 결과 출력
print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail())
Caution: Company performance prediction is a very complex problem, and the example above shows a simple time series prediction. More data and complex models are needed for more accurate predictions. News sentiment analysis results can be integrated into the model to improve prediction accuracy.
Step 4: Building a Streamlit Dashboard
Streamlit is a library that allows you to easily and quickly build data apps with Python. Build a dashboard that visually displays collected news data, sentiment analysis results, and company performance prediction results.
import streamlit as st
st.title("개인 맞춤형 투자 리서치 대시보드")
# 뉴스 데이터 표시
st.header("최근 뉴스")
if news:
for article in news:
st.subheader(article['title'])
st.write(article['description'])
st.write(f"감성: {analyze_sentiment(article['description'])}") # 감성 분석 결과 표시
st.write(f"[링크]({article['url']})")
st.write("---")
else:
st.write("뉴스 데이터를 가져오지 못했습니다.")
# 기업 실적 예측 결과 표시 (예시)
st.header("기업 실적 예측 (예시)")
try:
st.line_chart(forecast.set_index('ds')['yhat'])
except NameError:
st.write("기업 실적 예측 모델을 먼저 실행해주세요.")
How to Run: Save the above code as `app.py` and run the command `streamlit run app.py` in the terminal to view the dashboard in your web browser.
Tip: You can make the dashboard richer by utilizing various Streamlit components. For example, you can add stock charts, sentiment analysis result summaries, and portfolio simulations.
4. Real-world Use Case / Example
I use this dashboard to make stock investment decisions. For example, if there is a lot of positive news about a particular company, I buy its stock, and if there is a lot of negative news, I sell it. In the past, I had to read and analyze news articles one by one, but now I can check sentiment analysis results and make investment decisions in minutes through the dashboard. This dashboard has significantly reduced my investment research time and helped me achieve better investment performance.
5. Pros & Cons / Critical Analysis
- Pros:
- Time Savings: Significantly reduces investment research time through automated news analysis and sentiment analysis.
- Data-Driven Decision Making: Reduces subjective bias and enables investment decisions based on objective data.
- Personalized Information Provision: Provides customized information about companies and industries of interest.
- User-Friendly Interface: Streamlit allows for building easy and intuitive dashboards.
- Cons:
- Accuracy Issues: Sentiment analysis results may not be perfect, and false positives can occur.
- API Usage Costs: Costs may be incurred depending on NewsAPI and Llama 3 API usage.
- Model Building Complexity: Building a company performance prediction model requires advanced analytical skills, time, and effort.
- Data Dependency: The performance of the dashboard can be heavily influenced by the quality of the data.
6. FAQ
- Q: Can I use other LLMs instead of Llama 3?
A: Yes, of course. You can also use other LLMs such as GPT-3, GPT-4, or Bard. Compare the API usage and performance of each LLM to choose the appropriate model. - Q: Can I use other web frameworks instead of Streamlit?
A: Yes, you can also use other web frameworks like Flask or Django. However, Streamlit has the advantage of building data apps quickly and easily. - Q: What skills are needed to build a company performance prediction model?
A: Knowledge of statistics, machine learning, and data analysis is required. Additionally, experience with programming languages like Python, R, SQL, and related libraries is necessary.
7. Conclusion
A personalized investment research automation dashboard built on NewsAPI, Llama 3, and Streamlit can help individual investors overcome information overload and make data-driven, smart investment decisions. Follow the steps presented in this article to build your own dashboard and revolutionize your investment research process. Apply for a NewsAPI API key now and start news sentiment analysis using Llama 3!


