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