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
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
try:
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
# Basic Info
|
| 19 |
-
basic_info = pd.DataFrame([{
|
| 20 |
-
'Company Name': info.get('longName', 'N/A'),
|
| 21 |
-
'Sector': info.get('sector', 'N/A'),
|
| 22 |
-
'Industry': info.get('industry', 'N/A'),
|
| 23 |
-
'Market Cap': f"${info.get('marketCap', 0):,}",
|
| 24 |
-
'Current Price': f"${info.get('currentPrice', 0):.2f}",
|
| 25 |
-
'Previous Close': f"${info.get('previousClose', 0):.2f}",
|
| 26 |
-
'Open': f"${info.get('open', 0):.2f}",
|
| 27 |
-
'52 Week High': f"${info.get('fiftyTwoWeekHigh', 0):.2f}",
|
| 28 |
-
'52 Week Low': f"${info.get('fiftyTwoWeekLow', 0):.2f}",
|
| 29 |
-
'Volume': f"{info.get('volume', 0):,}",
|
| 30 |
-
'PE Ratio': f"{info.get('trailingPE', 0):.2f}",
|
| 31 |
-
'EPS': f"${info.get('trailingEps', 0):.2f}",
|
| 32 |
-
'Dividend Yield': f"{info.get('dividendYield', 0)*100:.2f}%" if info.get('dividendYield') else 'N/A',
|
| 33 |
-
'Beta': f"{info.get('beta', 0):.2f}",
|
| 34 |
-
}]).T
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
|
| 56 |
-
return f"Error analyzing {ticker}: {str(e)}\nPlease ensure you entered a valid ticker symbol."
|
| 57 |
-
|
| 58 |
-
# Create Gradio interface
|
| 59 |
-
iface = gr.Interface(
|
| 60 |
-
fn=analyze_stock,
|
| 61 |
-
inputs=gr.Textbox(label="Enter Stock Ticker Symbol (e.g., AAPL, MSFT)"),
|
| 62 |
-
outputs=gr.Textbox(label="Analysis Results", lines=20),
|
| 63 |
-
title="Comprehensive Stock Analysis Tool",
|
| 64 |
-
description="Enter a stock ticker symbol to get detailed analysis.",
|
| 65 |
-
examples=[["AAPL"], ["MSFT"], ["GOOGL"]]
|
| 66 |
-
)
|
| 67 |
|
|
|
|
| 68 |
if __name__ == "__main__":
|
| 69 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
+
import yfinance as yf
|
| 5 |
+
import requests
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import gradio as gr
|
| 8 |
+
from crewai import Crew, Agent, Task, Process
|
| 9 |
+
from langchain_openai import ChatOpenAI
|
| 10 |
+
from crewai_tools import tool
|
| 11 |
+
|
| 12 |
+
# API Keys setup
|
| 13 |
+
def setup_api_keys():
|
| 14 |
+
os.environ['OPENAI_API_KEY'] = "your-openai-api-key" # Replace with actual key
|
| 15 |
+
os.environ['NEWSAPI_KEY'] = "488e80d0ecb2485ca8f0f824cd9f7360"
|
| 16 |
+
|
| 17 |
+
# Stock Analysis Tools
|
| 18 |
+
@tool
|
| 19 |
+
def get_basic_stock_info(ticker: str) -> pd.DataFrame:
|
| 20 |
+
stock = yf.Ticker(ticker)
|
| 21 |
+
info = stock.info
|
| 22 |
+
|
| 23 |
+
basic_info = pd.DataFrame({
|
| 24 |
+
'Name': [info.get('longName', 'N/A')],
|
| 25 |
+
'Sector': [info.get('sector', 'N/A')],
|
| 26 |
+
'Industry': [info.get('industry', 'N/A')],
|
| 27 |
+
'Market Cap': [info.get('marketCap', 'N/A')],
|
| 28 |
+
'Current Price': [info.get('currentPrice', 'N/A')],
|
| 29 |
+
'52 Week High': [info.get('fiftyTwoWeekHigh', 'N/A')],
|
| 30 |
+
'52 Week Low': [info.get('fiftyTwoWeekLow', 'N/A')],
|
| 31 |
+
'Average Volume': [info.get('averageVolume', 'N/A')]
|
| 32 |
+
})
|
| 33 |
+
return basic_info
|
| 34 |
+
|
| 35 |
+
@tool
|
| 36 |
+
def get_fundamental_analysis(ticker: str, period: str = '1y') -> pd.DataFrame:
|
| 37 |
+
stock = yf.Ticker(ticker)
|
| 38 |
+
history = stock.history(period=period)
|
| 39 |
+
info = stock.info
|
| 40 |
+
|
| 41 |
+
fundamental_analysis = pd.DataFrame({
|
| 42 |
+
'PE Ratio': [info.get('trailingPE', 'N/A')],
|
| 43 |
+
'Forward PE': [info.get('forwardPE', 'N/A')],
|
| 44 |
+
'PEG Ratio': [info.get('pegRatio', 'N/A')],
|
| 45 |
+
'Price to Book': [info.get('priceToBook', 'N/A')],
|
| 46 |
+
'Dividend Yield': [info.get('dividendYield', 'N/A')],
|
| 47 |
+
'EPS (TTM)': [info.get('trailingEps', 'N/A')],
|
| 48 |
+
'Revenue Growth': [info.get('revenueGrowth', 'N/A')],
|
| 49 |
+
'Profit Margin': [info.get('profitMargins', 'N/A')],
|
| 50 |
+
'Free Cash Flow': [info.get('freeCashflow', 'N/A')],
|
| 51 |
+
'Debt to Equity': [info.get('debtToEquity', 'N/A')],
|
| 52 |
+
'Return on Equity': [info.get('returnOnEquity', 'N/A')],
|
| 53 |
+
'Operating Margin': [info.get('operatingMargins', 'N/A')],
|
| 54 |
+
'Quick Ratio': [info.get('quickRatio', 'N/A')],
|
| 55 |
+
'Current Ratio': [info.get('currentRatio', 'N/A')],
|
| 56 |
+
'Earnings Growth': [info.get('earningsGrowth', 'N/A')],
|
| 57 |
+
'Stock Price Avg (Period)': [history['Close'].mean()],
|
| 58 |
+
'Stock Price Max (Period)': [history['Close'].max()],
|
| 59 |
+
'Stock Price Min (Period)': [history['Close'].min()]
|
| 60 |
+
})
|
| 61 |
+
return fundamental_analysis
|
| 62 |
+
|
| 63 |
+
def calculate_beta(stock_returns, market_ticker, period):
|
| 64 |
+
market = yf.Ticker(market_ticker)
|
| 65 |
+
market_history = market.history(period=period)
|
| 66 |
+
market_returns = market_history['Close'].pct_change().dropna()
|
| 67 |
+
aligned_returns = pd.concat([stock_returns, market_returns], axis=1).dropna()
|
| 68 |
+
covariance = aligned_returns.cov().iloc[0, 1]
|
| 69 |
+
market_variance = market_returns.var()
|
| 70 |
+
return covariance / market_variance
|
| 71 |
+
|
| 72 |
+
def calculate_max_drawdown(prices):
|
| 73 |
+
peak = prices.cummax()
|
| 74 |
+
drawdown = (prices - peak) / peak
|
| 75 |
+
return drawdown.min()
|
| 76 |
+
|
| 77 |
+
def calculate_sharpe_ratio(returns, risk_free_rate=0.02):
|
| 78 |
+
excess_returns = returns - risk_free_rate/252
|
| 79 |
+
return np.sqrt(252) * excess_returns.mean() / excess_returns.std()
|
| 80 |
+
|
| 81 |
+
def calculate_sortino_ratio(returns, risk_free_rate=0.02, target_return=0):
|
| 82 |
+
excess_returns = returns - risk_free_rate/252
|
| 83 |
+
downside_returns = excess_returns[excess_returns < target_return]
|
| 84 |
+
downside_deviation = np.sqrt(np.mean(downside_returns**2))
|
| 85 |
+
return np.sqrt(252) * excess_returns.mean() / downside_deviation
|
| 86 |
+
|
| 87 |
+
@tool
|
| 88 |
+
def get_stock_risk_assessment(ticker: str, period: str = "1y") -> pd.DataFrame:
|
| 89 |
+
stock = yf.Ticker(ticker)
|
| 90 |
+
history = stock.history(period=period)
|
| 91 |
+
returns = history['Close'].pct_change().dropna()
|
| 92 |
+
|
| 93 |
+
volatility = returns.std() * np.sqrt(252)
|
| 94 |
+
beta = calculate_beta(returns, '^GSPC', period)
|
| 95 |
+
var_95 = np.percentile(returns, 5)
|
| 96 |
+
max_drawdown = calculate_max_drawdown(history['Close'])
|
| 97 |
+
|
| 98 |
+
risk_assessment = pd.DataFrame({
|
| 99 |
+
'Annualized Volatility': [volatility],
|
| 100 |
+
'Beta': [beta],
|
| 101 |
+
'Value at Risk (95%)': [var_95],
|
| 102 |
+
'Maximum Drawdown': [max_drawdown],
|
| 103 |
+
'Sharpe Ratio': [calculate_sharpe_ratio(returns)],
|
| 104 |
+
'Sortino Ratio': [calculate_sortino_ratio(returns)]
|
| 105 |
+
})
|
| 106 |
+
return risk_assessment
|
| 107 |
|
| 108 |
+
@tool
|
| 109 |
+
def get_technical_analysis(ticker: str, period: str = "1mo") -> pd.DataFrame:
|
| 110 |
+
stock = yf.Ticker(ticker)
|
| 111 |
+
history = stock.history(period=period)
|
| 112 |
|
| 113 |
+
# Calculate indicators
|
| 114 |
+
history['SMA_50'] = history['Close'].rolling(window=50).mean()
|
| 115 |
+
history['SMA_200'] = history['Close'].rolling(window=200).mean()
|
| 116 |
+
history['RSI'] = calculate_rsi(history['Close'])
|
| 117 |
+
history['MACD'], history['Signal'] = calculate_macd(history['Close'])
|
| 118 |
+
|
| 119 |
+
latest = history.iloc[-1]
|
| 120 |
+
|
| 121 |
+
analysis = pd.DataFrame({
|
| 122 |
+
'Indicator': [
|
| 123 |
+
'Current Price',
|
| 124 |
+
'50-day SMA',
|
| 125 |
+
'200-day SMA',
|
| 126 |
+
'RSI (14-day)',
|
| 127 |
+
'MACD',
|
| 128 |
+
'MACD Signal',
|
| 129 |
+
'Trend',
|
| 130 |
+
'MACD Signal',
|
| 131 |
+
'RSI Signal'
|
| 132 |
+
],
|
| 133 |
+
'Value': [
|
| 134 |
+
f'${latest["Close"]:.2f}',
|
| 135 |
+
f'${latest["SMA_50"]:.2f}',
|
| 136 |
+
f'${latest["SMA_200"]:.2f}',
|
| 137 |
+
f'{latest["RSI"]:.2f}',
|
| 138 |
+
f'{latest["MACD"]:.2f}',
|
| 139 |
+
f'{latest["Signal"]:.2f}',
|
| 140 |
+
analyze_trend(latest),
|
| 141 |
+
analyze_macd(latest),
|
| 142 |
+
analyze_rsi(latest)
|
| 143 |
+
]
|
| 144 |
+
})
|
| 145 |
+
return analysis
|
| 146 |
+
|
| 147 |
+
@tool
|
| 148 |
+
def get_stock_news(query: str, limit: int = 10, api_key: str = "488e80d0ecb2485ca8f0f824cd9f7360") -> pd.DataFrame:
|
| 149 |
+
base_url = "https://newsapi.org/v2/everything"
|
| 150 |
+
params = {
|
| 151 |
+
"q": query,
|
| 152 |
+
"language": "en",
|
| 153 |
+
"sortBy": "publishedAt",
|
| 154 |
+
"pageSize": limit,
|
| 155 |
+
"apiKey": api_key
|
| 156 |
+
}
|
| 157 |
|
| 158 |
try:
|
| 159 |
+
response = requests.get(base_url, params=params)
|
| 160 |
+
response.raise_for_status()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
+
data = response.json()
|
| 163 |
+
if "articles" not in data or not data["articles"]:
|
| 164 |
+
return pd.DataFrame({"Error": [f"No news found for query '{query}'."]})
|
| 165 |
+
|
| 166 |
+
articles = data["articles"]
|
| 167 |
+
news_data = []
|
| 168 |
+
for article in articles:
|
| 169 |
+
news_entry = {
|
| 170 |
+
"Title": article.get("title", "N/A"),
|
| 171 |
+
"Publisher": article.get("source", {}).get("name", "N/A"),
|
| 172 |
+
"Published": article.get("publishedAt", "N/A"),
|
| 173 |
+
"Link": article.get("url", "N/A")
|
| 174 |
+
}
|
| 175 |
+
news_data.append(news_entry)
|
| 176 |
+
|
| 177 |
+
return pd.DataFrame(news_data)
|
| 178 |
+
except requests.exceptions.RequestException as e:
|
| 179 |
+
return pd.DataFrame({"Error": [f"Failed to fetch news: {str(e)}"]})
|
| 180 |
|
| 181 |
+
# Initialize Agents and Tasks
|
| 182 |
+
def initialize_crew():
|
| 183 |
+
llm = ChatOpenAI(
|
| 184 |
+
model_name="gpt-4o-mini",
|
| 185 |
+
temperature=0.2,
|
| 186 |
+
max_tokens=2000,
|
| 187 |
+
top_p=0.95,
|
| 188 |
+
frequency_penalty=0.1,
|
| 189 |
+
presence_penalty=0.1,
|
| 190 |
+
streaming=False,
|
| 191 |
+
request_timeout=180
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
stock_researcher = Agent(
|
| 195 |
+
llm=llm,
|
| 196 |
+
role="Stock Researcher",
|
| 197 |
+
goal="Identify and research basic stock information",
|
| 198 |
+
backstory="Junior stock researcher specializing in gathering basic stock information",
|
| 199 |
+
tools=[get_basic_stock_info],
|
| 200 |
+
verbose=True,
|
| 201 |
+
allow_delegation=False
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
financial_analyst = Agent(
|
| 205 |
+
llm=llm,
|
| 206 |
+
role="Financial Analyst",
|
| 207 |
+
goal="Perform detailed stock analysis",
|
| 208 |
+
backstory="Seasoned financial analyst with expertise in complex financial data",
|
| 209 |
+
tools=[get_technical_analysis, get_fundamental_analysis, get_stock_risk_assessment],
|
| 210 |
+
verbose=True,
|
| 211 |
+
allow_delegation=False
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
news_analyst = Agent(
|
| 215 |
+
llm=llm,
|
| 216 |
+
role="News Analyst",
|
| 217 |
+
goal="Analyze stock-related news",
|
| 218 |
+
backstory="Sharp news analyst specializing in stock market news",
|
| 219 |
+
tools=[get_stock_news],
|
| 220 |
+
verbose=True
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
report_writer = Agent(
|
| 224 |
+
llm=llm,
|
| 225 |
+
role="Financial Report Writer",
|
| 226 |
+
goal="Create comprehensive stock reports",
|
| 227 |
+
backstory="Experienced financial writer",
|
| 228 |
+
tools=[],
|
| 229 |
+
verbose=True,
|
| 230 |
+
allow_delegation=False
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
return Crew(
|
| 234 |
+
agents=[stock_researcher, financial_analyst, news_analyst, report_writer],
|
| 235 |
+
tasks=[
|
| 236 |
+
collect_stock_info,
|
| 237 |
+
perform_analysis,
|
| 238 |
+
analyze_stock_news,
|
| 239 |
+
generate_stock_report
|
| 240 |
+
],
|
| 241 |
+
process=Process.sequential,
|
| 242 |
+
manager_llm=llm
|
| 243 |
+
)
|
| 244 |
|
| 245 |
+
def analyze_stock(query):
|
| 246 |
+
crew = initialize_crew()
|
| 247 |
+
default_date = datetime.now().date()
|
| 248 |
+
result = crew.kickoff(inputs={
|
| 249 |
+
"query": query,
|
| 250 |
+
"default_date": str(default_date),
|
| 251 |
+
"api_key": "488e80d0ecb2485ca8f0f824cd9f7360"
|
| 252 |
+
})
|
| 253 |
+
return f"### Analysis Report:\n\n{result}"
|
| 254 |
|
| 255 |
+
# Gradio Interface
|
| 256 |
+
def create_interface():
|
| 257 |
+
with gr.Blocks() as interface:
|
| 258 |
+
gr.Markdown("# Advanced Stock Analysis Dashboard")
|
| 259 |
+
gr.Markdown("Enter your Investment Query:")
|
| 260 |
+
|
| 261 |
+
query_input = gr.TextArea(
|
| 262 |
+
label="Your Financial ROBO Advisor",
|
| 263 |
+
value="Analyse ABC stock?",
|
| 264 |
+
lines=5,
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
analyze_button = gr.Button("Analyze")
|
| 268 |
+
analysis_output = gr.Markdown()
|
| 269 |
+
|
| 270 |
+
def on_analyze(query):
|
| 271 |
+
return analyze_stock(query)
|
| 272 |
+
|
| 273 |
+
analyze_button.click(on_analyze, inputs=[query_input], outputs=[analysis_output])
|
| 274 |
+
|
| 275 |
+
gr.Markdown("---")
|
| 276 |
+
gr.Markdown("Made by Manoj")
|
| 277 |
|
| 278 |
+
return interface
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
+
# Main execution
|
| 281 |
if __name__ == "__main__":
|
| 282 |
+
setup_api_keys()
|
| 283 |
+
interface = create_interface()
|
| 284 |
+
interface.launch()
|