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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import openai
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from getpass import getpass
|
| 7 |
+
#from google.colab import userdata
|
| 8 |
+
from langchain_core.prompts import PromptTemplate
|
| 9 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 10 |
+
from langchain.schema.runnable import RunnablePassthrough
|
| 11 |
+
from langchain_openai import ChatOpenAI
|
| 12 |
+
from transformers import pipeline
|
| 13 |
+
import yfinance as yf
|
| 14 |
+
from datetime import datetime
|
| 15 |
+
#import streamlit as stp
|
| 16 |
+
#from langchain_groq import ChatGroq
|
| 17 |
+
import streamlit as stp
|
| 18 |
+
from crewai import Crew, Agent, Task, Process
|
| 19 |
+
from crewai import Crew, Agent, Task, Process
|
| 20 |
+
#from langchain_groq import ChatGroq # This might also need to be installed using pip
|
| 21 |
+
try:
|
| 22 |
+
from crewai_tools import Tool
|
| 23 |
+
except ImportError:
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
from datetime import datetime
|
| 27 |
+
|
| 28 |
+
# Get current date/time
|
| 29 |
+
current_time = datetime.now()
|
| 30 |
+
#print(current_time)
|
| 31 |
+
|
| 32 |
+
#Read OPEN AI Key from user Data
|
| 33 |
+
#from google.colab import userdata
|
| 34 |
+
#api_key = os.getenv("OPENAI_API_KEY")
|
| 35 |
+
#os.environ['OPENAI_API_KEY'] = api_key
|
| 36 |
+
#openai.api_key = os.getenv('OPENAI_API_KEY')
|
| 37 |
+
#from google.colab import userdata
|
| 38 |
+
#api_key = os.get('NEWSAPI_KEY')
|
| 39 |
+
#os.environ['NEWSAPI_KEY'] = api_key
|
| 40 |
+
#openai.api_key = os.getenv('NEWSAPI_KEY')
|
| 41 |
+
|
| 42 |
+
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 43 |
+
newsapi_key = os.environ.get('NEWSAPI_KEY')
|
| 44 |
+
|
| 45 |
+
# Step 1: Define the Alpha Vantage Tool
|
| 46 |
+
#class AlphaVantageTool:
|
| 47 |
+
#def __init__(self, api_key):
|
| 48 |
+
#self.api_key = api_key
|
| 49 |
+
#self.base_url = "https://www.alphavantage.co/query"
|
| 50 |
+
|
| 51 |
+
# Initialize the tool with your API key
|
| 52 |
+
#api_key = "YS8AMMVFZXSLK6HF" # Replace with your actual API key
|
| 53 |
+
#alpha_tool = AlphaVantageTool(api_key)
|
| 54 |
+
|
| 55 |
+
from crewai_tools import tool
|
| 56 |
+
|
| 57 |
+
@tool
|
| 58 |
+
def get_basic_stock_info(ticker: str) -> pd.DataFrame:
|
| 59 |
+
"""Retrieves basic information about a single stock.
|
| 60 |
+
For more information, you can perform technical analysis, assess stock risk or perform fundamental analysis.
|
| 61 |
+
Params:
|
| 62 |
+
- ticker: The stock ticker symbol.
|
| 63 |
+
"""
|
| 64 |
+
stock = yf.Ticker(ticker)
|
| 65 |
+
info = stock.info
|
| 66 |
+
|
| 67 |
+
basic_info = pd.DataFrame({
|
| 68 |
+
'Name': [info.get('longName', 'N/A')],
|
| 69 |
+
'Sector': [info.get('sector', 'N/A')],
|
| 70 |
+
'Industry': [info.get('industry', 'N/A')],
|
| 71 |
+
'Market Cap': [info.get('marketCap', 'N/A')],
|
| 72 |
+
'Current Price': [info.get('currentPrice', 'N/A')],
|
| 73 |
+
'52 Week High': [info.get('fiftyTwoWeekHigh', 'N/A')],
|
| 74 |
+
'52 Week Low': [info.get('fiftyTwoWeekLow', 'N/A')],
|
| 75 |
+
'Average Volume': [info.get('averageVolume', 'N/A')]
|
| 76 |
+
})
|
| 77 |
+
return basic_info
|
| 78 |
+
|
| 79 |
+
@tool
|
| 80 |
+
def get_fundamental_analysis(ticker: str, period: str = '1y') -> pd.DataFrame:
|
| 81 |
+
"""
|
| 82 |
+
Performs fundamental analysis on a given stock for a specific period.
|
| 83 |
+
Params:
|
| 84 |
+
- ticker: The stock ticker symbol.
|
| 85 |
+
- period: The period to consider for historical data (default is 1 year) (available time-periods: ["1y", "2y", "5y", "10y", "ytd", "max"]).
|
| 86 |
+
Returns:
|
| 87 |
+
- DataFrame with fundamental metrics.
|
| 88 |
+
"""
|
| 89 |
+
stock = yf.Ticker(ticker)
|
| 90 |
+
|
| 91 |
+
# Fetch historical data for the given period
|
| 92 |
+
history = stock.history(period=period)
|
| 93 |
+
|
| 94 |
+
# Fetch latest available financial info
|
| 95 |
+
info = stock.info
|
| 96 |
+
|
| 97 |
+
fundamental_analysis = pd.DataFrame({
|
| 98 |
+
'PE Ratio': [info.get('trailingPE', 'N/A')],
|
| 99 |
+
'Forward PE': [info.get('forwardPE', 'N/A')],
|
| 100 |
+
'PEG Ratio': [info.get('pegRatio', 'N/A')],
|
| 101 |
+
'Price to Book': [info.get('priceToBook', 'N/A')],
|
| 102 |
+
'Dividend Yield': [info.get('dividendYield', 'N/A')],
|
| 103 |
+
'EPS (TTM)': [info.get('trailingEps', 'N/A')],
|
| 104 |
+
'Revenue Growth': [info.get('revenueGrowth', 'N/A')],
|
| 105 |
+
'Profit Margin': [info.get('profitMargins', 'N/A')],
|
| 106 |
+
'Free Cash Flow': [info.get('freeCashflow', 'N/A')],
|
| 107 |
+
'Debt to Equity': [info.get('debtToEquity', 'N/A')],
|
| 108 |
+
'Return on Equity': [info.get('returnOnEquity', 'N/A')],
|
| 109 |
+
'Operating Margin': [info.get('operatingMargins', 'N/A')],
|
| 110 |
+
'Quick Ratio': [info.get('quickRatio', 'N/A')],
|
| 111 |
+
'Current Ratio': [info.get('currentRatio', 'N/A')],
|
| 112 |
+
'Earnings Growth': [info.get('earningsGrowth', 'N/A')],
|
| 113 |
+
'Stock Price Avg (Period)': [history['Close'].mean()],
|
| 114 |
+
'Stock Price Max (Period)': [history['Close'].max()],
|
| 115 |
+
'Stock Price Min (Period)': [history['Close'].min()]
|
| 116 |
+
})
|
| 117 |
+
|
| 118 |
+
return fundamental_analysis
|
| 119 |
+
|
| 120 |
+
@tool
|
| 121 |
+
def get_stock_risk_assessment(ticker: str, period: str = "1y") -> pd.DataFrame:
|
| 122 |
+
"""Performs a risk assessment on a given stock.
|
| 123 |
+
Params:
|
| 124 |
+
- ticker: The stock ticker symbol.
|
| 125 |
+
- period: The time period for historical data (default: "1y").
|
| 126 |
+
"""
|
| 127 |
+
stock = yf.Ticker(ticker)
|
| 128 |
+
history = stock.history(period=period)
|
| 129 |
+
|
| 130 |
+
# Calculate daily returns
|
| 131 |
+
returns = history['Close'].pct_change().dropna()
|
| 132 |
+
|
| 133 |
+
# Calculate risk metrics
|
| 134 |
+
volatility = returns.std() * np.sqrt(252) # Annualized volatility
|
| 135 |
+
beta = calculate_beta(returns, '^GSPC', period) # Beta relative to S&P 500
|
| 136 |
+
var_95 = np.percentile(returns, 5) # 95% Value at Risk
|
| 137 |
+
max_drawdown = calculate_max_drawdown(history['Close'])
|
| 138 |
+
|
| 139 |
+
risk_assessment = pd.DataFrame({
|
| 140 |
+
'Annualized Volatility': [volatility],
|
| 141 |
+
'Beta': [beta],
|
| 142 |
+
'Value at Risk (95%)': [var_95],
|
| 143 |
+
'Maximum Drawdown': [max_drawdown],
|
| 144 |
+
'Sharpe Ratio': [calculate_sharpe_ratio(returns)],
|
| 145 |
+
'Sortino Ratio': [calculate_sortino_ratio(returns)]
|
| 146 |
+
})
|
| 147 |
+
|
| 148 |
+
return risk_assessment
|
| 149 |
+
|
| 150 |
+
def calculate_beta(stock_returns, market_ticker, period):
|
| 151 |
+
market = yf.Ticker(market_ticker)
|
| 152 |
+
market_history = market.history(period=period)
|
| 153 |
+
market_returns = market_history['Close'].pct_change().dropna()
|
| 154 |
+
|
| 155 |
+
# Align the dates of stock and market returns
|
| 156 |
+
aligned_returns = pd.concat([stock_returns, market_returns], axis=1).dropna()
|
| 157 |
+
|
| 158 |
+
covariance = aligned_returns.cov().iloc[0, 1]
|
| 159 |
+
market_variance = market_returns.var()
|
| 160 |
+
|
| 161 |
+
return covariance / market_variance
|
| 162 |
+
|
| 163 |
+
def calculate_max_drawdown(prices):
|
| 164 |
+
peak = prices.cummax()
|
| 165 |
+
drawdown = (prices - peak) / peak
|
| 166 |
+
return drawdown.min()
|
| 167 |
+
|
| 168 |
+
def calculate_sharpe_ratio(returns, risk_free_rate=0.02):
|
| 169 |
+
excess_returns = returns - risk_free_rate/252
|
| 170 |
+
return np.sqrt(252) * excess_returns.mean() / excess_returns.std()
|
| 171 |
+
|
| 172 |
+
def calculate_sortino_ratio(returns, risk_free_rate=0.02, target_return=0):
|
| 173 |
+
excess_returns = returns - risk_free_rate/252
|
| 174 |
+
downside_returns = excess_returns[excess_returns < target_return]
|
| 175 |
+
downside_deviation = np.sqrt(np.mean(downside_returns**2))
|
| 176 |
+
return np.sqrt(252) * excess_returns.mean() / downside_deviation
|
| 177 |
+
|
| 178 |
+
@tool
|
| 179 |
+
def get_technical_analysis(ticker: str, period: str = "1mo") -> pd.DataFrame:
|
| 180 |
+
"""Perform technical analysis on a given stock.
|
| 181 |
+
Params:
|
| 182 |
+
- ticker: The stock ticker symbol.
|
| 183 |
+
- period: The time period for historical data (available time-periods: ["1d", "5d", "1mo", "3mo", "6mo"]).
|
| 184 |
+
"""
|
| 185 |
+
stock = yf.Ticker(ticker)
|
| 186 |
+
history = stock.history(period=period)
|
| 187 |
+
|
| 188 |
+
# Calculate indicators
|
| 189 |
+
history['SMA_50'] = history['Close'].rolling(window=50).mean()
|
| 190 |
+
history['SMA_200'] = history['Close'].rolling(window=200).mean()
|
| 191 |
+
history['RSI'] = calculate_rsi(history['Close'])
|
| 192 |
+
history['MACD'], history['Signal'] = calculate_macd(history['Close'])
|
| 193 |
+
|
| 194 |
+
latest = history.iloc[-1]
|
| 195 |
+
|
| 196 |
+
analysis = pd.DataFrame({
|
| 197 |
+
'Indicator': [
|
| 198 |
+
'Current Price',
|
| 199 |
+
'50-day SMA',
|
| 200 |
+
'200-day SMA',
|
| 201 |
+
'RSI (14-day)',
|
| 202 |
+
'MACD',
|
| 203 |
+
'MACD Signal',
|
| 204 |
+
'Trend',
|
| 205 |
+
'MACD Signal',
|
| 206 |
+
'RSI Signal'
|
| 207 |
+
],
|
| 208 |
+
'Value': [
|
| 209 |
+
f'${latest["Close"]:.2f}',
|
| 210 |
+
f'${latest["SMA_50"]:.2f}',
|
| 211 |
+
f'${latest["SMA_200"]:.2f}',
|
| 212 |
+
f'{latest["RSI"]:.2f}',
|
| 213 |
+
f'{latest["MACD"]:.2f}',
|
| 214 |
+
f'{latest["Signal"]:.2f}',
|
| 215 |
+
analyze_trend(latest),
|
| 216 |
+
analyze_macd(latest),
|
| 217 |
+
analyze_rsi(latest)
|
| 218 |
+
]
|
| 219 |
+
})
|
| 220 |
+
|
| 221 |
+
return analysis
|
| 222 |
+
|
| 223 |
+
import requests
|
| 224 |
+
import pandas as pd
|
| 225 |
+
import os
|
| 226 |
+
#from google.colab import output
|
| 227 |
+
|
| 228 |
+
# Retrieve API key
|
| 229 |
+
@tool
|
| 230 |
+
def get_stock_news(query: str, limit: int = 10, api_key: str = "26d4fec27a7f4f28b17c791b653e25b3") -> pd.DataFrame:
|
| 231 |
+
"""
|
| 232 |
+
Fetches recent news articles related to a specific stock using NewsAPI.
|
| 233 |
+
Params:
|
| 234 |
+
- query: Search term (e.g., stock ticker or company name).
|
| 235 |
+
- limit: The number of news articles to fetch.
|
| 236 |
+
- api_key: 488e80d0ecb2485ca8f0f824cd9f7360
|
| 237 |
+
Returns:
|
| 238 |
+
- A Pandas DataFrame containing the latest news articles.
|
| 239 |
+
"""
|
| 240 |
+
base_url = "https://newsapi.org/v2/everything"
|
| 241 |
+
params = {
|
| 242 |
+
"q": query,
|
| 243 |
+
"language": "en",
|
| 244 |
+
"sortBy": "publishedAt",
|
| 245 |
+
"pageSize": limit,
|
| 246 |
+
"apiKey": api_key
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
try:
|
| 250 |
+
response = requests.get(base_url, params=params)
|
| 251 |
+
response.raise_for_status() # Raise HTTP errors if any
|
| 252 |
+
|
| 253 |
+
data = response.json()
|
| 254 |
+
if "articles" not in data or not data["articles"]:
|
| 255 |
+
return pd.DataFrame({"Error": [f"No news found for query '{query}'."]})
|
| 256 |
+
|
| 257 |
+
# Extract and format news articles
|
| 258 |
+
articles = data["articles"]
|
| 259 |
+
news_data = []
|
| 260 |
+
for article in articles:
|
| 261 |
+
news_entry = {
|
| 262 |
+
"Title": article.get("title", "N/A"),
|
| 263 |
+
"Publisher": article.get("source", {}).get("name", "N/A"),
|
| 264 |
+
"Published": article.get("publishedAt", "N/A"),
|
| 265 |
+
"Link": article.get("url", "N/A")
|
| 266 |
+
}
|
| 267 |
+
news_data.append(news_entry)
|
| 268 |
+
|
| 269 |
+
return pd.DataFrame(news_data)
|
| 270 |
+
except requests.exceptions.RequestException as e:
|
| 271 |
+
return pd.DataFrame({"Error": [f"Failed to fetch news: {str(e)}"]})
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def calculate_rsi(series, period=14):
|
| 277 |
+
delta = series.diff()
|
| 278 |
+
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
|
| 279 |
+
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
|
| 280 |
+
rs = gain / loss
|
| 281 |
+
rsi = 100 - (100 / (1 + rs))
|
| 282 |
+
return rsi
|
| 283 |
+
|
| 284 |
+
def calculate_macd(series, short_window=12, long_window=26, signal_window=9):
|
| 285 |
+
short_ema = series.ewm(span=short_window, adjust=False).mean()
|
| 286 |
+
long_ema = series.ewm(span=long_window, adjust=False).mean()
|
| 287 |
+
macd = short_ema - long_ema
|
| 288 |
+
signal = macd.ewm(span=signal_window, adjust=False).mean()
|
| 289 |
+
return macd, signal
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def analyze_trend(latest):
|
| 293 |
+
if latest['Close'] > latest['SMA_50'] > latest['SMA_200']:
|
| 294 |
+
return "Bullish"
|
| 295 |
+
elif latest['Close'] < latest['SMA_50'] < latest['SMA_200']:
|
| 296 |
+
return "Bearish"
|
| 297 |
+
else:
|
| 298 |
+
return "Neutral"
|
| 299 |
+
|
| 300 |
+
def analyze_macd(latest):
|
| 301 |
+
if latest['MACD'] > latest['Signal']:
|
| 302 |
+
return "Bullish"
|
| 303 |
+
else:
|
| 304 |
+
return "Bearish"
|
| 305 |
+
|
| 306 |
+
def analyze_rsi(latest):
|
| 307 |
+
if latest['RSI'] > 70:
|
| 308 |
+
return "Overbought"
|
| 309 |
+
elif latest['RSI'] < 30:
|
| 310 |
+
return "Oversold"
|
| 311 |
+
else:
|
| 312 |
+
return "Neutral"
|
| 313 |
+
|
| 314 |
+
def analyze_bollinger_bands(latest):
|
| 315 |
+
if latest['Close'] > latest['BB_Upper']:
|
| 316 |
+
return "Price above upper band (potential overbought)"
|
| 317 |
+
elif latest['Close'] < latest['BB_Lower']:
|
| 318 |
+
return "Price below lower band (potential oversold)"
|
| 319 |
+
else:
|
| 320 |
+
return "Price within bands"
|
| 321 |
+
|
| 322 |
+
def format_number(self, value):
|
| 323 |
+
if value != 'N/A':
|
| 324 |
+
return f'${value:,.2f}'
|
| 325 |
+
else:
|
| 326 |
+
return 'N/A'
|
| 327 |
+
|
| 328 |
+
def interpret_pe_ratio(self, trailing_pe):
|
| 329 |
+
if trailing_pe < 15:
|
| 330 |
+
return "Undervalued"
|
| 331 |
+
elif trailing_pe > 30:
|
| 332 |
+
return "Overvalued"
|
| 333 |
+
else:
|
| 334 |
+
return "Neutral"
|
| 335 |
+
|
| 336 |
+
def interpret_price_to_book(self, price_to_book):
|
| 337 |
+
if price_to_book < 1:
|
| 338 |
+
return "Undervalued"
|
| 339 |
+
elif price_to_book > 3:
|
| 340 |
+
return "Overvalued"
|
| 341 |
+
else:
|
| 342 |
+
return "Neutral"
|
| 343 |
+
|
| 344 |
+
# Load Model wtih parameters
|
| 345 |
+
|
| 346 |
+
from langchain_openai import ChatOpenAI
|
| 347 |
+
|
| 348 |
+
llm = ChatOpenAI(
|
| 349 |
+
model_name="gpt-4o-mini", # Specifies which model to use
|
| 350 |
+
temperature=0.2, # Controls randomness in responses
|
| 351 |
+
max_tokens=2000, # Maximum length of response
|
| 352 |
+
top_p=0.95, # Cumulative probability for token sampling
|
| 353 |
+
frequency_penalty=0.1, # Reduces repetition of similar words
|
| 354 |
+
presence_penalty=0.1, # Encourages discussing new topics
|
| 355 |
+
streaming=False, # Enables/disables incremental response output
|
| 356 |
+
request_timeout=180 # Maximum API response wait time
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
from langchain_openai import ChatOpenAI
|
| 360 |
+
from crewai import Agent
|
| 361 |
+
|
| 362 |
+
# Initialize the language model
|
| 363 |
+
llm = ChatOpenAI(model_name="gpt-4o-mini")
|
| 364 |
+
|
| 365 |
+
stock_researcher = Agent(
|
| 366 |
+
llm=llm, # Pass the initialized language model instance
|
| 367 |
+
role="Stock Researcher",
|
| 368 |
+
goal="Identify the stock and the stock ticker, and if you already have the stock ticker and if it's necessary, get basic stock info about the selected stock.",
|
| 369 |
+
backstory="An junior stock researcher with a knack for gathering relevant, basic information about stocks, the relevant company/companies, the industry, and some basic info about stock's performance",
|
| 370 |
+
tools=[get_basic_stock_info],
|
| 371 |
+
verbose=True,
|
| 372 |
+
allow_delegation=False
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
financial_analyst = Agent(
|
| 376 |
+
llm=llm,
|
| 377 |
+
role="Financial Analyst",
|
| 378 |
+
goal="Perform in-depth fundamental and technical analysis on the stock, focusing on aspects most relevant to the user's query",
|
| 379 |
+
backstory="A seasoned financial analyst with expertise in interpreting complex financial data and translating it into insights tailored to various levels of financial literacy",
|
| 380 |
+
tools=[get_technical_analysis, get_fundamental_analysis, get_stock_risk_assessment],
|
| 381 |
+
verbose=True,
|
| 382 |
+
allow_delegation=False
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
news_analyst = Agent(
|
| 386 |
+
llm=llm,
|
| 387 |
+
role="News Analyst",
|
| 388 |
+
goal="Fetch recent news articles related to the stock and their potential impact on performance",
|
| 389 |
+
backstory="A sharp news analyst who can quickly digest information, assess its relevance to stock performance, and provide concise summaries",
|
| 390 |
+
tools=[get_stock_news],
|
| 391 |
+
verbose=True
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
report_writer = Agent(
|
| 395 |
+
role='Financial Report Writer',
|
| 396 |
+
goal='Synthesize all analysis into a cohesive, professional stock report',
|
| 397 |
+
backstory='Experienced financial writer with a talent for clear, concise reporting',
|
| 398 |
+
tools=[],
|
| 399 |
+
verbose=True,
|
| 400 |
+
allow_delegation=False,
|
| 401 |
+
llm=llm
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
collect_stock_info = Task(
|
| 405 |
+
description='''
|
| 406 |
+
1. Extract the ticker of the stock (or stocks) mentioned in the user query as well as the timeframe (if mentioned). If the ticker is not provided, use the query to identify the stock ticker.
|
| 407 |
+
2. If the query implies a novice user, prepare brief explanations for key financial terms. If nothing is mentioned, assume that the user has an above average understanding of financial terms.
|
| 408 |
+
Expect only basic stock info from this task.
|
| 409 |
+
User query: {query}.
|
| 410 |
+
Your response should be on the basis of:
|
| 411 |
+
Ticker: [identified stock ticker]
|
| 412 |
+
Timeframe: [identified timeframe]
|
| 413 |
+
Analysis Focus: [identified focus of analysis]
|
| 414 |
+
User Expertise: [implied level of financial expertise]
|
| 415 |
+
Key Concerns: [specific concerns or priorities mentioned]
|
| 416 |
+
News from the API key : [488e80d0ecb2485ca8f0f824cd9f7360]
|
| 417 |
+
''',
|
| 418 |
+
expected_output="A summary of the stock's key financial metrics and performance, tailored to the user's query.",
|
| 419 |
+
agent=stock_researcher,
|
| 420 |
+
dependencies=[],
|
| 421 |
+
context=[]
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
perform_analysis = Task(
|
| 425 |
+
description='''
|
| 426 |
+
Conduct a thorough analysis of the stock, tailored to the user's query and expertise level.
|
| 427 |
+
1. Use the get_stock_info, get_fundamental_analysis, get_stock_risk_assessment and get_technical_analysis tools as needed, based on the query's focus. E.g. If the query is about the fundamentals of a stock, then technical info need not be present.
|
| 428 |
+
2. Focus on metrics and trends most relevant to the user's specific question and identified timeframe.
|
| 429 |
+
3. Provide clear explanations of complex financial concepts if the query suggests a novice user.
|
| 430 |
+
4. Relate the analysis directly to the key concerns identified in the query interpretation.
|
| 431 |
+
5. Consider both historical performance and future projections in your analysis..
|
| 432 |
+
User query: {query}.
|
| 433 |
+
''',
|
| 434 |
+
expected_output="A detailed analysis of the stock's financial and/or technical performance, directly addressing the user's query and concerns.",
|
| 435 |
+
agent=financial_analyst,
|
| 436 |
+
dependencies=[collect_stock_info],
|
| 437 |
+
context=[collect_stock_info]
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
analyze_stock_news = Task(
|
| 441 |
+
description='''
|
| 442 |
+
1. Use the get_stock_news tool to fetch recent news related to the stock.
|
| 443 |
+
2. Conclude with an overall assessment including the sentiment of how recent news might influence the stock in the relevant timeframe.
|
| 444 |
+
NOTE: Re-fetching news will get you the same results.
|
| 445 |
+
''',
|
| 446 |
+
expected_output="A summary of recent news articles related to the stock and their potential impact on performance.",
|
| 447 |
+
agent=news_analyst,
|
| 448 |
+
dependencies=[collect_stock_info],
|
| 449 |
+
context=[collect_stock_info]
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
generate_stock_report = Task(
|
| 453 |
+
description='''
|
| 454 |
+
Synthesize all the collected information and analyses into a stock report tailored to the user's specific query.
|
| 455 |
+
The report should:
|
| 456 |
+
1. Begin with an Executive Summary that directly addresses the user's question
|
| 457 |
+
2. Include relevant sections based on the query's focus
|
| 458 |
+
3. Provide an Investment Recommendation that specifically answers the user's query
|
| 459 |
+
4. Conclude with a summary that ties all insights back to the original question
|
| 460 |
+
Ensure that:
|
| 461 |
+
- The report directly answers the user's specific question
|
| 462 |
+
- The language and depth of analysis match the user's level of expertise implied by the query
|
| 463 |
+
- The report highlights factors most relevant to the user's identified concerns and timeframe
|
| 464 |
+
- Clear, professional language is used throughout, with well-reasoned insights
|
| 465 |
+
- The report is in markdown format for easy reading and formatting
|
| 466 |
+
- The report should be crisp but detailed. You can reiterate important points but avoid redundancy.
|
| 467 |
+
- You are an expert in the field, so you should be confident in your answer, requiring no further action/analysis from the user. It is your job to give a clear recommendation.
|
| 468 |
+
- The report should contain only the relevant info. E.g. if the query is about the fundamentals of a stock, then technical info need not be present.
|
| 469 |
+
User query: {query}.
|
| 470 |
+
''',
|
| 471 |
+
expected_output="A comprehensive stock report in markdown format, addressing all aspects of the user's query and providing a clear investment recommendation.",
|
| 472 |
+
agent=report_writer,
|
| 473 |
+
dependencies=[collect_stock_info],
|
| 474 |
+
context=[collect_stock_info, perform_analysis, analyze_stock_news]
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
crew = Crew(
|
| 478 |
+
agents=[stock_researcher, financial_analyst, news_analyst, report_writer],
|
| 479 |
+
tasks=[
|
| 480 |
+
collect_stock_info,
|
| 481 |
+
perform_analysis,
|
| 482 |
+
analyze_stock_news,
|
| 483 |
+
generate_stock_report
|
| 484 |
+
],
|
| 485 |
+
process=Process.sequential,
|
| 486 |
+
manager_llm=llm
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
import yfinance as yf
|
| 490 |
+
|
| 491 |
+
# Define 'query' and 'default_date' before calling crew.kickoff
|
| 492 |
+
query = "Microsoft stock analysis??" # Replace with your desired query
|
| 493 |
+
import datetime
|
| 494 |
+
default_date = datetime.date.today()
|
| 495 |
+
crew.kickoff(inputs={
|
| 496 |
+
"query": query,
|
| 497 |
+
"default_date": str(default_date),
|
| 498 |
+
"api_key": "488e80d0ecb2485ca8f0f824cd9f7360" # Add the API key here
|
| 499 |
+
})
|
| 500 |
+
|
| 501 |
+
from datetime import datetime
|
| 502 |
+
|
| 503 |
+
def analyze_stock(query):
|
| 504 |
+
"""Perform stock analysis using the given query."""
|
| 505 |
+
# Simulate the analysis process
|
| 506 |
+
default_date = datetime.now().date()
|
| 507 |
+
result = crew.kickoff(inputs={"query": query, "default_date": str(default_date)})
|
| 508 |
+
return f"### Analysis Report:\n\n{result}"
|
| 509 |
+
|
| 510 |
+
# Define the Gradio interface
|
| 511 |
+
with gr.Blocks() as interface:
|
| 512 |
+
gr.Markdown("# Advanced Stock Analysis Dashboard")
|
| 513 |
+
gr.Markdown("Enter your Investment Query:")
|
| 514 |
+
|
| 515 |
+
query_input = gr.TextArea(
|
| 516 |
+
label="Your Financial ROBO Advisor",
|
| 517 |
+
value="Analyse ABC stock?",
|
| 518 |
+
lines=5,
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
analyze_button = gr.Button("Analyze")
|
| 522 |
+
analysis_output = gr.Markdown()
|
| 523 |
+
|
| 524 |
+
def on_analyze(query):
|
| 525 |
+
return analyze_stock(query)
|
| 526 |
+
|
| 527 |
+
analyze_button.click(on_analyze, inputs=[query_input], outputs=[analysis_output])
|
| 528 |
+
|
| 529 |
+
gr.Markdown("---")
|
| 530 |
+
gr.Markdown("Made by GEN_AI Team 4")
|
| 531 |
+
|
| 532 |
+
# Launch the interface
|
| 533 |
+
interface.launch()
|