rupt123 commited on
Commit
dee787f
·
verified ·
1 Parent(s): 8ddd525

Update app.py

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