vibesurf 0.1.22__py3-none-any.whl → 0.1.24__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of vibesurf might be problematic. Click here for more details.

@@ -0,0 +1,586 @@
1
+ """
2
+ Comprehensive finance tools using Yahoo Finance API.
3
+ Provides access to stock market data, company financials, and trading information.
4
+ """
5
+ import pdb
6
+ from enum import Enum
7
+ from typing import Dict, List, Any, Optional, Union
8
+ from datetime import datetime, timedelta
9
+ import yfinance as yf
10
+ import pandas as pd
11
+ from vibe_surf.logger import get_logger
12
+
13
+ logger = get_logger(__name__)
14
+
15
+
16
+ class FinanceMethod(Enum):
17
+ """Available Yahoo Finance data methods"""
18
+ # Basic Information
19
+ GET_INFO = "get_info" # Company basic information
20
+ GET_FAST_INFO = "get_fast_info" # Quick stats like current price, volume
21
+
22
+ # Market Data & History
23
+ GET_HISTORY = "get_history" # Historical price and volume data
24
+ GET_ACTIONS = "get_actions" # Dividends and stock splits
25
+ GET_DIVIDENDS = "get_dividends" # Dividend history
26
+ GET_SPLITS = "get_splits" # Stock split history
27
+ GET_CAPITAL_GAINS = "get_capital_gains" # Capital gains distributions
28
+
29
+ # Financial Statements
30
+ GET_FINANCIALS = "get_financials" # Income statement (annual)
31
+ GET_QUARTERLY_FINANCIALS = "get_quarterly_financials" # Income statement (quarterly)
32
+ GET_BALANCE_SHEET = "get_balance_sheet" # Balance sheet (annual)
33
+ GET_QUARTERLY_BALANCE_SHEET = "get_quarterly_balance_sheet" # Balance sheet (quarterly)
34
+ GET_CASHFLOW = "get_cashflow" # Cash flow statement (annual)
35
+ GET_QUARTERLY_CASHFLOW = "get_quarterly_cashflow" # Cash flow statement (quarterly)
36
+
37
+ # Earnings & Analysis
38
+ GET_EARNINGS = "get_earnings" # Historical earnings data
39
+ GET_QUARTERLY_EARNINGS = "get_quarterly_earnings" # Quarterly earnings
40
+ GET_EARNINGS_DATES = "get_earnings_dates" # Upcoming earnings dates
41
+ GET_CALENDAR = "get_calendar" # Earnings calendar
42
+
43
+ # Recommendations & Analysis
44
+ GET_RECOMMENDATIONS = "get_recommendations" # Analyst recommendations
45
+ GET_RECOMMENDATIONS_SUMMARY = "get_recommendations_summary" # Summary of recommendations
46
+ GET_UPGRADES_DOWNGRADES = "get_upgrades_downgrades" # Rating changes
47
+ GET_ANALYSIS = "get_analysis" # Analyst analysis
48
+
49
+ # Ownership & Holdings
50
+ GET_MAJOR_HOLDERS = "get_major_holders" # Major shareholders
51
+ GET_INSTITUTIONAL_HOLDERS = "get_institutional_holders" # Institutional holdings
52
+ GET_MUTUALFUND_HOLDERS = "get_mutualfund_holders" # Mutual fund holdings
53
+ GET_INSIDER_PURCHASES = "get_insider_purchases" # Insider purchases
54
+ GET_INSIDER_TRANSACTIONS = "get_insider_transactions" # Insider transactions
55
+ GET_INSIDER_ROSTER_HOLDERS = "get_insider_roster_holders" # Insider roster
56
+
57
+ # Additional Data
58
+ GET_NEWS = "get_news" # Latest news
59
+ GET_SUSTAINABILITY = "get_sustainability" # ESG scores
60
+ GET_SEC_FILINGS = "get_sec_filings" # SEC filings
61
+ GET_SHARES = "get_shares" # Share count data
62
+
63
+ # Options (if applicable)
64
+ GET_OPTIONS = "get_options" # Option chain data
65
+
66
+
67
+ class FinanceDataRetriever:
68
+ """Main class for retrieving and formatting Yahoo Finance data"""
69
+
70
+ def __init__(self, symbol: str):
71
+ """Initialize with stock symbol"""
72
+ self.symbol = symbol.upper()
73
+ self.ticker = yf.Ticker(self.symbol)
74
+
75
+ def get_finance_data(self, methods: List[str], **kwargs) -> Dict[str, Any]:
76
+ """
77
+ Retrieve finance data using specified methods
78
+
79
+ Args:
80
+ methods: List of method names (FinanceMethod enum values)
81
+ **kwargs: Additional parameters (e.g., period, start_date, end_date, num_news)
82
+
83
+ Returns:
84
+ Dictionary with method names as keys and data as values
85
+ """
86
+ results = {}
87
+
88
+ for method in methods:
89
+ try:
90
+ if hasattr(self, f"_{method}"):
91
+ method_func = getattr(self, f"_{method}")
92
+ results[method] = method_func(**kwargs)
93
+ else:
94
+ results[method] = f"Error: Method {method} not implemented"
95
+ logger.warning(f"Method {method} not implemented for {self.symbol}")
96
+ except Exception as e:
97
+ error_msg = f"Error retrieving {method}: {str(e)}"
98
+ results[method] = error_msg
99
+ logger.error(f"Error retrieving {method} for {self.symbol}: {e}")
100
+
101
+ return results
102
+
103
+ # Basic Information Methods
104
+ def _get_info(self, **kwargs) -> Dict:
105
+ """Get basic company information"""
106
+ return self.ticker.info
107
+
108
+ def _get_fast_info(self, **kwargs) -> Dict:
109
+ """Get quick statistics"""
110
+ try:
111
+ fast_info = self.ticker.fast_info
112
+ return dict(fast_info) if hasattr(fast_info, '__dict__') else fast_info
113
+ except:
114
+ return self.ticker.get_fast_info()
115
+
116
+ # Market Data & History Methods
117
+ def _get_history(self, **kwargs) -> pd.DataFrame:
118
+ """Get historical price and volume data"""
119
+ period = kwargs.get('period', '1y')
120
+ start_date = kwargs.get('start_date')
121
+ end_date = kwargs.get('end_date')
122
+ interval = kwargs.get('interval', '1d')
123
+
124
+ if start_date and end_date:
125
+ return self.ticker.history(start=start_date, end=end_date, interval=interval)
126
+ else:
127
+ return self.ticker.history(period=period, interval=interval)
128
+
129
+ def _get_actions(self, **kwargs) -> pd.DataFrame:
130
+ """Get dividend and stock split history"""
131
+ return self.ticker.actions
132
+
133
+ def _get_dividends(self, **kwargs) -> pd.Series:
134
+ """Get dividend history"""
135
+ return self.ticker.dividends
136
+
137
+ def _get_splits(self, **kwargs) -> pd.Series:
138
+ """Get stock split history"""
139
+ return self.ticker.splits
140
+
141
+ def _get_capital_gains(self, **kwargs) -> pd.Series:
142
+ """Get capital gains distributions"""
143
+ return self.ticker.capital_gains
144
+
145
+ # Financial Statements Methods
146
+ def _get_financials(self, **kwargs) -> pd.DataFrame:
147
+ """Get annual income statement"""
148
+ return self.ticker.financials
149
+
150
+ def _get_quarterly_financials(self, **kwargs) -> pd.DataFrame:
151
+ """Get quarterly income statement"""
152
+ return self.ticker.quarterly_financials
153
+
154
+ def _get_balance_sheet(self, **kwargs) -> pd.DataFrame:
155
+ """Get annual balance sheet"""
156
+ return self.ticker.balance_sheet
157
+
158
+ def _get_quarterly_balance_sheet(self, **kwargs) -> pd.DataFrame:
159
+ """Get quarterly balance sheet"""
160
+ return self.ticker.quarterly_balance_sheet
161
+
162
+ def _get_cashflow(self, **kwargs) -> pd.DataFrame:
163
+ """Get annual cash flow statement"""
164
+ return self.ticker.cashflow
165
+
166
+ def _get_quarterly_cashflow(self, **kwargs) -> pd.DataFrame:
167
+ """Get quarterly cash flow statement"""
168
+ return self.ticker.quarterly_cashflow
169
+
170
+ # Earnings & Analysis Methods
171
+ def _get_earnings(self, **kwargs) -> pd.DataFrame:
172
+ """Get historical earnings data"""
173
+ return self.ticker.earnings
174
+
175
+ def _get_quarterly_earnings(self, **kwargs) -> pd.DataFrame:
176
+ """Get quarterly earnings data"""
177
+ return self.ticker.quarterly_earnings
178
+
179
+ def _get_earnings_dates(self, **kwargs) -> pd.DataFrame:
180
+ """Get earnings dates and estimates"""
181
+ return self.ticker.earnings_dates
182
+
183
+ def _get_calendar(self, **kwargs) -> Dict:
184
+ """Get earnings calendar"""
185
+ return self.ticker.calendar
186
+
187
+ # Recommendations & Analysis Methods
188
+ def _get_recommendations(self, **kwargs) -> pd.DataFrame:
189
+ """Get analyst recommendations history"""
190
+ return self.ticker.recommendations
191
+
192
+ def _get_recommendations_summary(self, **kwargs) -> pd.DataFrame:
193
+ """Get summary of analyst recommendations"""
194
+ return self.ticker.recommendations_summary
195
+
196
+ def _get_upgrades_downgrades(self, **kwargs) -> pd.DataFrame:
197
+ """Get analyst upgrades and downgrades"""
198
+ return self.ticker.upgrades_downgrades
199
+
200
+ def _get_analysis(self, **kwargs) -> pd.DataFrame:
201
+ """Get analyst analysis"""
202
+ return getattr(self.ticker, 'analysis', pd.DataFrame())
203
+
204
+ # Ownership & Holdings Methods
205
+ def _get_major_holders(self, **kwargs) -> pd.DataFrame:
206
+ """Get major shareholders"""
207
+ return self.ticker.major_holders
208
+
209
+ def _get_institutional_holders(self, **kwargs) -> pd.DataFrame:
210
+ """Get institutional holdings"""
211
+ return self.ticker.institutional_holders
212
+
213
+ def _get_mutualfund_holders(self, **kwargs) -> pd.DataFrame:
214
+ """Get mutual fund holdings"""
215
+ return self.ticker.mutualfund_holders
216
+
217
+ def _get_insider_purchases(self, **kwargs) -> pd.DataFrame:
218
+ """Get insider purchases"""
219
+ return getattr(self.ticker, 'insider_purchases', pd.DataFrame())
220
+
221
+ def _get_insider_transactions(self, **kwargs) -> pd.DataFrame:
222
+ """Get insider transactions"""
223
+ return getattr(self.ticker, 'insider_transactions', pd.DataFrame())
224
+
225
+ def _get_insider_roster_holders(self, **kwargs) -> pd.DataFrame:
226
+ """Get insider roster"""
227
+ return getattr(self.ticker, 'insider_roster_holders', pd.DataFrame())
228
+
229
+ # Additional Data Methods
230
+ def _get_news(self, **kwargs) -> List[Dict]:
231
+ """Get latest news"""
232
+ num_news = kwargs.get('num_news', 5)
233
+ news = self.ticker.news
234
+ return news[:num_news] if news else []
235
+
236
+ def _get_sustainability(self, **kwargs) -> pd.DataFrame:
237
+ """Get ESG sustainability data"""
238
+ return getattr(self.ticker, 'sustainability', pd.DataFrame())
239
+
240
+ def _get_sec_filings(self, **kwargs) -> pd.DataFrame:
241
+ """Get SEC filings"""
242
+ return getattr(self.ticker, 'sec_filings', pd.DataFrame())
243
+
244
+ def _get_shares(self, **kwargs) -> pd.DataFrame:
245
+ """Get share count data"""
246
+ return getattr(self.ticker, 'shares', pd.DataFrame())
247
+
248
+ def _get_options(self, **kwargs) -> Dict:
249
+ """Get options data"""
250
+ try:
251
+ option_dates = self.ticker.options
252
+ if option_dates:
253
+ # Get the first available expiration date
254
+ first_expiry = option_dates[0]
255
+ opt_chain = self.ticker.option_chain(first_expiry)
256
+ return {
257
+ 'expiration_dates': list(option_dates),
258
+ 'calls': opt_chain.calls,
259
+ 'puts': opt_chain.puts,
260
+ 'selected_expiry': first_expiry
261
+ }
262
+ return {'expiration_dates': [], 'calls': pd.DataFrame(), 'puts': pd.DataFrame()}
263
+ except:
264
+ return {'error': 'Options data not available for this ticker'}
265
+
266
+
267
+ class FinanceMarkdownFormatter:
268
+ """Formats finance data into markdown"""
269
+
270
+ @staticmethod
271
+ def format_finance_data(symbol: str, results: Dict[str, Any], methods: List[str]) -> str:
272
+ """Format all finance data as markdown"""
273
+ markdown = f"# 💹 Financial Data for {symbol.upper()}\n\n"
274
+
275
+ for method in methods:
276
+ data = results.get(method)
277
+
278
+ if isinstance(data, str) and data.startswith('Error'):
279
+ markdown += f"## ❌ {method.replace('_', ' ').title()}\n{data}\n\n"
280
+ continue
281
+
282
+ markdown += f"## 📊 {method.replace('_', ' ').title()}\n\n"
283
+
284
+ # Route to appropriate formatter
285
+ formatter_method = f"_format_{method}"
286
+ if hasattr(FinanceMarkdownFormatter, formatter_method):
287
+ formatter = getattr(FinanceMarkdownFormatter, formatter_method)
288
+ markdown += formatter(data)
289
+ else:
290
+ # Generic formatter for unhandled methods
291
+ markdown += FinanceMarkdownFormatter._format_generic(data)
292
+
293
+ markdown += "\n\n"
294
+
295
+ return markdown.strip()
296
+
297
+ @staticmethod
298
+ def _format_generic(data: Any) -> str:
299
+ """Generic formatter for any data type"""
300
+ if data is None or (hasattr(data, 'empty') and data.empty):
301
+ return "No data available.\n"
302
+
303
+ if isinstance(data, pd.DataFrame):
304
+ if len(data) == 0:
305
+ return "No data available.\n"
306
+ return f"```\n{data.to_string()}\n```\n"
307
+ elif isinstance(data, pd.Series):
308
+ if len(data) == 0:
309
+ return "No data available.\n"
310
+ return f"```\n{data.to_string()}\n```\n"
311
+ elif isinstance(data, (list, dict)):
312
+ import json
313
+ return f"```json\n{json.dumps(data, indent=2, default=str)}\n```\n"
314
+ else:
315
+ return f"```\n{str(data)}\n```\n"
316
+
317
+ @staticmethod
318
+ def _format_get_info(info: Dict) -> str:
319
+ """Format company info as markdown"""
320
+ if not info:
321
+ return "No company information available.\n"
322
+
323
+ markdown = ""
324
+
325
+ # Basic company info
326
+ if 'longName' in info:
327
+ markdown += f"**Company Name:** {info['longName']}\n"
328
+ if 'sector' in info:
329
+ markdown += f"**Sector:** {info['sector']}\n"
330
+ if 'industry' in info:
331
+ markdown += f"**Industry:** {info['industry']}\n"
332
+ if 'website' in info:
333
+ markdown += f"**Website:** {info['website']}\n"
334
+ if 'country' in info:
335
+ markdown += f"**Country:** {info['country']}\n"
336
+
337
+ markdown += "\n### 💰 Financial Metrics\n"
338
+
339
+ # Financial metrics
340
+ if 'marketCap' in info and info['marketCap']:
341
+ markdown += f"**Market Cap:** ${info['marketCap']:,.0f}\n"
342
+ if 'enterpriseValue' in info and info['enterpriseValue']:
343
+ markdown += f"**Enterprise Value:** ${info['enterpriseValue']:,.0f}\n"
344
+ if 'totalRevenue' in info and info['totalRevenue']:
345
+ markdown += f"**Total Revenue:** ${info['totalRevenue']:,.0f}\n"
346
+ if 'grossMargins' in info and info['grossMargins']:
347
+ markdown += f"**Gross Margin:** {info['grossMargins']:.2%}\n"
348
+ if 'profitMargins' in info and info['profitMargins']:
349
+ markdown += f"**Profit Margin:** {info['profitMargins']:.2%}\n"
350
+
351
+ markdown += "\n### 📈 Stock Price Info\n"
352
+
353
+ # Stock price info
354
+ if 'currentPrice' in info and info['currentPrice']:
355
+ markdown += f"**Current Price:** ${info['currentPrice']:.2f}\n"
356
+ if 'previousClose' in info and info['previousClose']:
357
+ markdown += f"**Previous Close:** ${info['previousClose']:.2f}\n"
358
+ if 'fiftyTwoWeekHigh' in info and info['fiftyTwoWeekHigh']:
359
+ markdown += f"**52 Week High:** ${info['fiftyTwoWeekHigh']:.2f}\n"
360
+ if 'fiftyTwoWeekLow' in info and info['fiftyTwoWeekLow']:
361
+ markdown += f"**52 Week Low:** ${info['fiftyTwoWeekLow']:.2f}\n"
362
+ if 'dividendYield' in info and info['dividendYield']:
363
+ markdown += f"**Dividend Yield:** {info['dividendYield']:.2%}\n"
364
+
365
+ # Business summary
366
+ if 'longBusinessSummary' in info:
367
+ summary = info['longBusinessSummary'][:500]
368
+ if len(info['longBusinessSummary']) > 500:
369
+ summary += "..."
370
+ markdown += f"\n### 📋 Business Summary\n{summary}\n"
371
+
372
+ return markdown
373
+
374
+ @staticmethod
375
+ def _format_get_fast_info(fast_info) -> str:
376
+ """Format fast info as markdown"""
377
+ if not fast_info:
378
+ return "No fast info available.\n"
379
+
380
+ markdown = ""
381
+
382
+ # Convert to dict if needed
383
+ if hasattr(fast_info, '__dict__'):
384
+ data = fast_info.__dict__
385
+ elif isinstance(fast_info, dict):
386
+ data = fast_info
387
+ else:
388
+ return f"Fast info data: {str(fast_info)}\n"
389
+
390
+ # Format key metrics
391
+ for key, value in data.items():
392
+ if value is not None:
393
+ key_formatted = key.replace('_', ' ').title()
394
+ if isinstance(value, (int, float)):
395
+ if 'price' in key.lower() or 'value' in key.lower():
396
+ markdown += f"**{key_formatted}:** ${value:,.2f}\n"
397
+ elif 'volume' in key.lower():
398
+ markdown += f"**{key_formatted}:** {value:,}\n"
399
+ else:
400
+ markdown += f"**{key_formatted}:** {value}\n"
401
+ else:
402
+ markdown += f"**{key_formatted}:** {value}\n"
403
+
404
+ return markdown
405
+
406
+ @staticmethod
407
+ def _format_get_history(history: pd.DataFrame) -> str:
408
+ """Format historical data as markdown"""
409
+ if history.empty:
410
+ return "No historical data available.\n"
411
+
412
+ markdown = f"**Period:** {history.index.min().strftime('%Y-%m-%d')} to {history.index.max().strftime('%Y-%m-%d')}\n"
413
+ markdown += f"**Total Records:** {len(history)}\n\n"
414
+
415
+ # Determine how much data to show based on total records
416
+ total_records = len(history)
417
+ if total_records <= 30:
418
+ # Show all data if 30 records or less
419
+ display_data = history
420
+ markdown += f"### 📈 Historical Data (All {total_records} Records)\n\n"
421
+ else:
422
+ # Show recent 30 records for larger datasets
423
+ display_data = history.tail(30)
424
+ markdown += f"### 📈 Recent Data (Last 30 Records)\n\n"
425
+
426
+ markdown += "| Date | Open | High | Low | Close | Volume |\n"
427
+ markdown += "|------|------|------|-----|-------|--------|\n"
428
+
429
+ for date, row in display_data.iterrows():
430
+ markdown += f"| {date.strftime('%Y-%m-%d')} | ${row['Open']:.2f} | ${row['High']:.2f} | ${row['Low']:.2f} | ${row['Close']:.2f} | {row['Volume']:,} |\n"
431
+
432
+ # Summary statistics
433
+ markdown += "\n### 📊 Summary Statistics\n"
434
+ markdown += f"**Highest Price:** ${history['High'].max():.2f}\n"
435
+ markdown += f"**Lowest Price:** ${history['Low'].min():.2f}\n"
436
+ markdown += f"**Average Volume:** {history['Volume'].mean():,.0f}\n"
437
+ markdown += f"**Total Volume:** {history['Volume'].sum():,}\n"
438
+
439
+ return markdown
440
+
441
+ @staticmethod
442
+ def _format_get_news(news: List[Dict]) -> str:
443
+ """Format news data as markdown"""
444
+ if not news:
445
+ return "No news available.\n"
446
+
447
+ markdown = f"**Total News Articles:** {len(news)}\n\n"
448
+ pdb.set_trace()
449
+ for i, article in enumerate(news, 1):
450
+ if isinstance(article, dict):
451
+ # Try different possible field names for title
452
+ title = (article.get('title') or
453
+ article.get('headline') or
454
+ article.get('summary') or
455
+ 'No title available')
456
+
457
+ # Try different possible field names for link/URL
458
+ link = (article.get('link') or
459
+ article.get('url') or
460
+ article.get('guid') or '')
461
+
462
+ # Try different possible field names for publisher
463
+ publisher = (article.get('publisher') or
464
+ article.get('source') or
465
+ article.get('author') or
466
+ 'Unknown')
467
+
468
+ # Try different possible field names for timestamp
469
+ publish_time = (article.get('providerPublishTime') or
470
+ article.get('timestamp') or
471
+ article.get('pubDate') or
472
+ article.get('published') or '')
473
+
474
+ markdown += f"### {i}. {title}\n"
475
+ markdown += f"**Publisher:** {publisher}\n"
476
+
477
+ if publish_time:
478
+ try:
479
+ # Handle different timestamp formats
480
+ if isinstance(publish_time, (int, float)):
481
+ dt = datetime.fromtimestamp(publish_time)
482
+ markdown += f"**Published:** {dt.strftime('%Y-%m-%d %H:%M')}\n"
483
+ elif isinstance(publish_time, str):
484
+ # Try to parse string timestamp
485
+ try:
486
+ publish_time_int = int(float(publish_time))
487
+ dt = datetime.fromtimestamp(publish_time_int)
488
+ markdown += f"**Published:** {dt.strftime('%Y-%m-%d %H:%M')}\n"
489
+ except:
490
+ markdown += f"**Published:** {publish_time}\n"
491
+ except Exception as e:
492
+ # If timestamp parsing fails, show raw value
493
+ markdown += f"**Published:** {publish_time}\n"
494
+
495
+ if link:
496
+ markdown += f"**Link:** {link}\n"
497
+
498
+ # Add summary or description if available
499
+ summary = (article.get('summary') or
500
+ article.get('description') or
501
+ article.get('snippet') or '')
502
+ if summary and summary != title:
503
+ # Limit summary length
504
+ if len(summary) > 200:
505
+ summary = summary[:200] + "..."
506
+ markdown += f"**Summary:** {summary}\n"
507
+
508
+ markdown += "\n"
509
+
510
+ return markdown
511
+
512
+ @staticmethod
513
+ def _format_get_dividends(dividends: pd.Series) -> str:
514
+ """Format dividend data as markdown"""
515
+ if dividends.empty:
516
+ return "No dividend data available.\n"
517
+
518
+ markdown = f"**Total Dividends Recorded:** {len(dividends)}\n"
519
+ markdown += f"**Date Range:** {dividends.index.min().strftime('%Y-%m-%d')} to {dividends.index.max().strftime('%Y-%m-%d')}\n\n"
520
+
521
+ # Recent dividends (last 10)
522
+ recent_dividends = dividends.tail(10)
523
+ markdown += "### 💰 Recent Dividends\n\n"
524
+ markdown += "| Date | Dividend Amount |\n"
525
+ markdown += "|------|----------------|\n"
526
+
527
+ for date, amount in recent_dividends.items():
528
+ markdown += f"| {date.strftime('%Y-%m-%d')} | ${amount:.4f} |\n"
529
+
530
+ # Summary
531
+ markdown += f"\n**Total Dividends Paid:** ${dividends.sum():.4f}\n"
532
+ markdown += f"**Average Dividend:** ${dividends.mean():.4f}\n"
533
+ if len(dividends) > 1:
534
+ yearly_frequency = len(dividends) / ((dividends.index.max() - dividends.index.min()).days / 365.25)
535
+ markdown += f"**Estimated Annual Frequency:** {yearly_frequency:.1f} times per year\n"
536
+
537
+ return markdown
538
+
539
+ @staticmethod
540
+ def _format_get_recommendations(recommendations: pd.DataFrame) -> str:
541
+ """Format recommendations as markdown"""
542
+ if recommendations.empty:
543
+ return "No recommendations available.\n"
544
+
545
+ markdown = f"**Total Recommendations:** {len(recommendations)}\n\n"
546
+
547
+ # Recent recommendations (last 15)
548
+ recent_recs = recommendations.tail(15)
549
+ markdown += "### 📊 Recent Analyst Recommendations\n\n"
550
+ markdown += "| Date | Firm | To Grade | From Grade | Action |\n"
551
+ markdown += "|------|------|----------|------------|--------|\n"
552
+
553
+ for _, rec in recent_recs.iterrows():
554
+ date = rec.get('Date', 'N/A')
555
+ firm = rec.get('Firm', 'N/A')
556
+ to_grade = rec.get('To Grade', 'N/A')
557
+ from_grade = rec.get('From Grade', 'N/A')
558
+ action = rec.get('Action', 'N/A')
559
+
560
+ markdown += f"| {date} | {firm} | {to_grade} | {from_grade} | {action} |\n"
561
+
562
+ return markdown
563
+
564
+ @staticmethod
565
+ def _format_get_earnings(earnings: pd.DataFrame) -> str:
566
+ """Format earnings as markdown"""
567
+ if earnings.empty:
568
+ return "No earnings data available.\n"
569
+
570
+ markdown = "### 💼 Annual Earnings History\n\n"
571
+ markdown += "| Year | Revenue | Earnings |\n"
572
+ markdown += "|------|---------|----------|\n"
573
+
574
+ for year, row in earnings.iterrows():
575
+ revenue = row.get('Revenue', 'N/A')
576
+ earnings_val = row.get('Earnings', 'N/A')
577
+
578
+ # Format numbers if they're numeric
579
+ if isinstance(revenue, (int, float)):
580
+ revenue = f"${revenue:,.0f}"
581
+ if isinstance(earnings_val, (int, float)):
582
+ earnings_val = f"${earnings_val:,.0f}"
583
+
584
+ markdown += f"| {year} | {revenue} | {earnings_val} |\n"
585
+
586
+ return markdown
@@ -2,11 +2,12 @@ from browser_use.tools.registry.service import Registry
2
2
  from vibe_surf.tools.vibesurf_tools import VibeSurfTools
3
3
  from vibe_surf.tools.file_system import CustomFileSystem
4
4
  from browser_use.tools.views import NoParamsAction
5
+ from vibe_surf.tools.vibesurf_registry import VibeSurfRegistry
5
6
 
6
7
 
7
8
  class ReportWriterTools(VibeSurfTools):
8
9
  def __init__(self, exclude_actions: list[str] = []):
9
- self.registry = Registry(exclude_actions)
10
+ self.registry = VibeSurfRegistry(exclude_actions)
10
11
  self._register_file_actions()
11
12
  self._register_done_action()
12
13
 
@@ -0,0 +1,52 @@
1
+ from browser_use.tools.registry.service import Registry, Context
2
+ import asyncio
3
+ import functools
4
+ import inspect
5
+ import logging
6
+ import re
7
+ from collections.abc import Callable
8
+ from inspect import Parameter, iscoroutinefunction, signature
9
+ from types import UnionType
10
+ from typing import Any, Generic, Optional, TypeVar, Union, get_args, get_origin
11
+
12
+ import pyotp
13
+ from pydantic import BaseModel, Field, RootModel, create_model
14
+
15
+ from browser_use.browser import BrowserSession
16
+ from browser_use.filesystem.file_system import FileSystem
17
+ from browser_use.llm.base import BaseChatModel
18
+ from browser_use.observability import observe_debug
19
+ from browser_use.telemetry.service import ProductTelemetry
20
+ from browser_use.tools.registry.views import (
21
+ ActionModel,
22
+ ActionRegistry,
23
+ RegisteredAction,
24
+ SpecialActionParameters,
25
+ )
26
+ from browser_use.utils import is_new_tab_page, match_url_with_domain_pattern, time_execution_async
27
+
28
+ from vibe_surf.logger import get_logger
29
+ from vibe_surf.browser.browser_manager import BrowserManager
30
+
31
+ logger = get_logger(__name__)
32
+
33
+
34
+ class VibeSurfRegistry(Registry):
35
+ def _get_special_param_types(self) -> dict[str, type | UnionType | None]:
36
+ """Get the expected types for special parameters from SpecialActionParameters"""
37
+ # Manually define the expected types to avoid issues with Optional handling.
38
+ # we should try to reduce this list to 0 if possible, give as few standardized objects to all the actions
39
+ # but each driver should decide what is relevant to expose the action methods,
40
+ # e.g. CDP client, 2fa code getters, sensitive_data wrappers, other context, etc.
41
+ return {
42
+ 'context': None, # Context is a TypeVar, so we can't validate type
43
+ 'browser_session': BrowserSession,
44
+ 'page_url': str,
45
+ 'cdp_client': None, # CDPClient type from cdp_use, but we don't import it here
46
+ 'page_extraction_llm': BaseChatModel,
47
+ 'available_file_paths': list,
48
+ 'has_sensitive_data': bool,
49
+ 'file_system': FileSystem,
50
+ 'llm': BaseChatModel,
51
+ 'browser_manager': BrowserManager
52
+ }