openmarkets 0.1.0.dev43__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.
@@ -0,0 +1,298 @@
1
+ """Extended market data tools for yfinance MCP server."""
2
+
3
+ import json
4
+ from typing import List, Optional
5
+
6
+ import yfinance as yf
7
+ from mcp.server import FastMCP
8
+
9
+
10
+ def register_extended_market_tools(mcp: FastMCP):
11
+ """Register extended market data tools with the MCP server."""
12
+
13
+ @mcp.tool()
14
+ async def download_bulk_data(
15
+ tickers: List[str],
16
+ period: str = "1mo",
17
+ interval: str = "1d",
18
+ group_by: str = "ticker",
19
+ auto_adjust: bool = True,
20
+ prepost: bool = False,
21
+ threads: bool = True,
22
+ ) -> str:
23
+ """Download bulk historical data for multiple tickers efficiently.
24
+
25
+ Args:
26
+ tickers: List of ticker symbols
27
+ period: Data period (1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max)
28
+ interval: Data interval (1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo)
29
+ group_by: Group by 'ticker' or 'column'
30
+ auto_adjust: Auto-adjust prices for dividends and splits
31
+ prepost: Include pre and post market data
32
+ threads: Use threading for faster downloads
33
+
34
+ Returns:
35
+ JSON string containing bulk historical data
36
+ """
37
+ try:
38
+ data = yf.download(
39
+ tickers=" ".join(tickers),
40
+ period=period,
41
+ interval=interval,
42
+ group_by=group_by,
43
+ auto_adjust=auto_adjust,
44
+ prepost=prepost,
45
+ threads=threads,
46
+ )
47
+
48
+ if data.empty:
49
+ return json.dumps({"error": "No data available for the given tickers"})
50
+
51
+ return json.dumps(
52
+ {"tickers": tickers, "period": period, "interval": interval, "data": data.to_dict()},
53
+ indent=2,
54
+ default=str,
55
+ )
56
+
57
+ except Exception as e:
58
+ return json.dumps({"error": f"Failed to download bulk data: {str(e)}"})
59
+
60
+ @mcp.tool()
61
+ async def get_ticker_history_metadata(ticker: str) -> str:
62
+ """Get comprehensive ticker history metadata.
63
+
64
+ Args:
65
+ ticker: Stock ticker symbol
66
+
67
+ Returns:
68
+ JSON string containing history metadata
69
+ """
70
+ try:
71
+ stock = yf.Ticker(ticker)
72
+
73
+ # Get different types of historical data metadata
74
+ metadata = {
75
+ "symbol": ticker,
76
+ "available_periods": ["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max"],
77
+ "available_intervals": [
78
+ "1m",
79
+ "2m",
80
+ "5m",
81
+ "15m",
82
+ "30m",
83
+ "60m",
84
+ "90m",
85
+ "1h",
86
+ "1d",
87
+ "5d",
88
+ "1wk",
89
+ "1mo",
90
+ "3mo",
91
+ ],
92
+ }
93
+
94
+ # Try to get some sample data to verify ticker exists
95
+ try:
96
+ hist = stock.history(period="5d")
97
+ if not hist.empty:
98
+ metadata["data_available"] = True
99
+ metadata["latest_date"] = str(hist.index[-1])
100
+ metadata["earliest_available"] = str(hist.index[0])
101
+ metadata["columns"] = list(hist.columns)
102
+ else:
103
+ metadata["data_available"] = False
104
+ except Exception:
105
+ metadata["data_available"] = False
106
+
107
+ return json.dumps(metadata, indent=2)
108
+
109
+ except Exception as e:
110
+ return json.dumps({"error": f"Failed to get metadata: {str(e)}"})
111
+
112
+ @mcp.tool()
113
+ async def get_exchange_info(ticker: str) -> str:
114
+ """Get detailed exchange and trading information.
115
+
116
+ Args:
117
+ ticker: Stock ticker symbol
118
+
119
+ Returns:
120
+ JSON string containing exchange information
121
+ """
122
+ try:
123
+ stock = yf.Ticker(ticker)
124
+ info = stock.info
125
+
126
+ exchange_info = {
127
+ "symbol": ticker,
128
+ "exchange": info.get("exchange"),
129
+ "fullExchangeName": info.get("fullExchangeName"),
130
+ "exchangeTimezoneName": info.get("exchangeTimezoneName"),
131
+ "exchangeTimezoneShortName": info.get("exchangeTimezoneShortName"),
132
+ "market": info.get("market"),
133
+ "marketState": info.get("marketState"),
134
+ "quoteType": info.get("quoteType"),
135
+ "currency": info.get("currency"),
136
+ "financialCurrency": info.get("financialCurrency"),
137
+ "gmtOffSetMilliseconds": info.get("gmtOffSetMilliseconds"),
138
+ "regularMarketTime": info.get("regularMarketTime"),
139
+ "preMarketTime": info.get("preMarketTime"),
140
+ "postMarketTime": info.get("postMarketTime"),
141
+ "tradeable": info.get("tradeable"),
142
+ "triggerable": info.get("triggerable"),
143
+ }
144
+
145
+ return json.dumps(exchange_info, indent=2, default=str)
146
+
147
+ except Exception as e:
148
+ return json.dumps({"error": f"Failed to get exchange info: {str(e)}"})
149
+
150
+ @mcp.tool()
151
+ async def get_market_hours(ticker: str) -> str:
152
+ """Get market hours and session information.
153
+
154
+ Args:
155
+ ticker: Stock ticker symbol
156
+
157
+ Returns:
158
+ JSON string containing market hours data
159
+ """
160
+ try:
161
+ stock = yf.Ticker(ticker)
162
+ info = stock.info
163
+
164
+ market_hours = {
165
+ "symbol": ticker,
166
+ "exchange": info.get("exchange"),
167
+ "timezone": info.get("exchangeTimezoneName"),
168
+ "marketState": info.get("marketState"),
169
+ "regularMarketTime": info.get("regularMarketTime"),
170
+ "regularMarketPrice": info.get("regularMarketPrice"),
171
+ "regularMarketPreviousClose": info.get("regularMarketPreviousClose"),
172
+ "preMarketPrice": info.get("preMarketPrice"),
173
+ "preMarketChange": info.get("preMarketChange"),
174
+ "preMarketChangePercent": info.get("preMarketChangePercent"),
175
+ "preMarketTime": info.get("preMarketTime"),
176
+ "postMarketPrice": info.get("postMarketPrice"),
177
+ "postMarketChange": info.get("postMarketChange"),
178
+ "postMarketChangePercent": info.get("postMarketChangePercent"),
179
+ "postMarketTime": info.get("postMarketTime"),
180
+ }
181
+
182
+ return json.dumps(market_hours, indent=2, default=str)
183
+
184
+ except Exception as e:
185
+ return json.dumps({"error": f"Failed to get market hours: {str(e)}"})
186
+
187
+ @mcp.tool()
188
+ async def validate_tickers(tickers: List[str]) -> str:
189
+ """Validate a list of ticker symbols.
190
+
191
+ Args:
192
+ tickers: List of ticker symbols to validate
193
+
194
+ Returns:
195
+ JSON string containing validation results
196
+ """
197
+ try:
198
+ validation_results = []
199
+
200
+ for ticker in tickers:
201
+ try:
202
+ stock = yf.Ticker(ticker)
203
+
204
+ # Try to get basic info to validate ticker
205
+ info = stock.info
206
+ hist = stock.history(period="2d")
207
+
208
+ is_valid = bool(info.get("symbol") and not hist.empty)
209
+
210
+ validation_results.append(
211
+ {
212
+ "ticker": ticker,
213
+ "valid": is_valid,
214
+ "name": info.get("shortName") if is_valid else None,
215
+ "exchange": info.get("exchange") if is_valid else None,
216
+ "quoteType": info.get("quoteType") if is_valid else None,
217
+ }
218
+ )
219
+
220
+ except Exception:
221
+ validation_results.append({"ticker": ticker, "valid": False, "error": "Failed to retrieve data"})
222
+
223
+ valid_count = sum(1 for result in validation_results if result["valid"])
224
+
225
+ return json.dumps(
226
+ {
227
+ "total_tickers": len(tickers),
228
+ "valid_count": valid_count,
229
+ "invalid_count": len(tickers) - valid_count,
230
+ "results": validation_results,
231
+ },
232
+ indent=2,
233
+ )
234
+
235
+ except Exception as e:
236
+ return json.dumps({"error": f"Failed to validate tickers: {str(e)}"})
237
+
238
+ @mcp.tool()
239
+ async def get_currency_data(base_currency: str = "USD", target_currencies: Optional[List[str]] = None) -> str:
240
+ """Get currency exchange rate data.
241
+
242
+ Args:
243
+ base_currency: Base currency code (e.g., 'USD')
244
+ target_currencies: List of target currency codes (default: major currencies)
245
+
246
+ Returns:
247
+ JSON string containing currency data
248
+ """
249
+ try:
250
+ if target_currencies is None:
251
+ target_currencies = ["EUR", "GBP", "JPY", "CAD", "AUD", "CHF", "CNY"]
252
+
253
+ currency_data = []
254
+
255
+ for target in target_currencies:
256
+ if target == base_currency:
257
+ continue
258
+
259
+ currency_pair = f"{base_currency}{target}=X"
260
+
261
+ try:
262
+ ticker = yf.Ticker(currency_pair)
263
+ hist = ticker.history(period="2d")
264
+ info = ticker.info
265
+
266
+ if not hist.empty:
267
+ current_rate = hist.iloc[-1]["Close"]
268
+
269
+ # Calculate daily change if we have enough data
270
+ daily_change = None
271
+ daily_change_percent = None
272
+ if len(hist) >= 2:
273
+ previous_rate = hist.iloc[-2]["Close"]
274
+ daily_change = current_rate - previous_rate
275
+ daily_change_percent = (daily_change / previous_rate) * 100
276
+
277
+ currency_data.append(
278
+ {
279
+ "pair": currency_pair,
280
+ "base": base_currency,
281
+ "target": target,
282
+ "rate": current_rate,
283
+ "daily_change": daily_change,
284
+ "daily_change_percent": daily_change_percent,
285
+ "name": info.get("shortName"),
286
+ }
287
+ )
288
+
289
+ except Exception:
290
+ # Skip currencies that cause errors
291
+ continue
292
+
293
+ return json.dumps(
294
+ {"base_currency": base_currency, "currency_rates": currency_data, "count": len(currency_data)}, indent=2
295
+ )
296
+
297
+ except Exception as e:
298
+ return json.dumps({"error": f"Failed to get currency data: {str(e)}"})
@@ -0,0 +1,140 @@
1
+ """Financial statements tools."""
2
+
3
+ import json
4
+
5
+ import yfinance as yf
6
+ from mcp.server import FastMCP
7
+
8
+
9
+ def register_financial_statements_tools(mcp: FastMCP):
10
+ """Register financial statements tools with the MCP server."""
11
+
12
+ @mcp.tool()
13
+ async def get_income_statement(ticker: str, quarterly: bool = False) -> str:
14
+ """Get income statement data.
15
+
16
+ Args:
17
+ ticker: Stock ticker symbol
18
+ quarterly: If True, get quarterly data; if False, get annual data
19
+
20
+ Returns:
21
+ JSON string containing income statement data
22
+ """
23
+ stock = yf.Ticker(ticker)
24
+ if quarterly:
25
+ financials = stock.quarterly_income_stmt
26
+ else:
27
+ financials = stock.income_stmt
28
+
29
+ if financials is not None and not financials.empty:
30
+ return financials.to_json(date_format="iso")
31
+ return json.dumps({"error": "No income statement data available"})
32
+
33
+ @mcp.tool()
34
+ async def get_balance_sheet(ticker: str, quarterly: bool = False) -> str:
35
+ """Get balance sheet data.
36
+
37
+ Args:
38
+ ticker: Stock ticker symbol
39
+ quarterly: If True, get quarterly data; if False, get annual data
40
+
41
+ Returns:
42
+ JSON string containing balance sheet data
43
+ """
44
+ stock = yf.Ticker(ticker)
45
+ if quarterly:
46
+ balance_sheet = stock.quarterly_balance_sheet
47
+ else:
48
+ balance_sheet = stock.balance_sheet
49
+
50
+ if balance_sheet is not None and not balance_sheet.empty:
51
+ return balance_sheet.to_json(date_format="iso")
52
+ return json.dumps({"error": "No balance sheet data available"})
53
+
54
+ @mcp.tool()
55
+ async def get_cash_flow(ticker: str, quarterly: bool = False) -> str:
56
+ """Get cash flow statement data.
57
+
58
+ Args:
59
+ ticker: Stock ticker symbol
60
+ quarterly: If True, get quarterly data; if False, get annual data
61
+
62
+ Returns:
63
+ JSON string containing cash flow data
64
+ """
65
+ stock = yf.Ticker(ticker)
66
+ if quarterly:
67
+ cashflow = stock.quarterly_cashflow
68
+ else:
69
+ cashflow = stock.cashflow
70
+
71
+ if cashflow is not None and not cashflow.empty:
72
+ return cashflow.to_json(date_format="iso")
73
+ return json.dumps({"error": "No cash flow data available"})
74
+
75
+ @mcp.tool()
76
+ async def get_earnings(ticker: str) -> str:
77
+ """Get annual earnings data.
78
+
79
+ Args:
80
+ ticker: Stock ticker symbol
81
+
82
+ Returns:
83
+ JSON string containing annual earnings data
84
+ """
85
+ stock = yf.Ticker(ticker)
86
+ earnings = stock.earnings
87
+ if earnings is not None and not earnings.empty:
88
+ return earnings.to_json(date_format="iso")
89
+ return json.dumps({"error": "No earnings data available"})
90
+
91
+ @mcp.tool()
92
+ async def get_quarterly_earnings(ticker: str) -> str:
93
+ """Get quarterly earnings data.
94
+
95
+ Args:
96
+ ticker: Stock ticker symbol
97
+
98
+ Returns:
99
+ JSON string containing quarterly earnings data
100
+ """
101
+ stock = yf.Ticker(ticker)
102
+ earnings = stock.quarterly_earnings
103
+ if earnings is not None and not earnings.empty:
104
+ return earnings.to_json(date_format="iso")
105
+ return json.dumps({"error": "No quarterly earnings data available"})
106
+
107
+ @mcp.tool()
108
+ async def get_financials_summary(ticker: str) -> str:
109
+ """Get key financial metrics summary.
110
+
111
+ Args:
112
+ ticker: Stock ticker symbol
113
+
114
+ Returns:
115
+ JSON string containing financial summary
116
+ """
117
+ stock = yf.Ticker(ticker)
118
+ info = stock.info
119
+
120
+ financial_summary = {
121
+ "totalRevenue": info.get("totalRevenue"),
122
+ "revenueGrowth": info.get("revenueGrowth"),
123
+ "grossProfits": info.get("grossProfits"),
124
+ "grossMargins": info.get("grossMargins"),
125
+ "operatingMargins": info.get("operatingMargins"),
126
+ "profitMargins": info.get("profitMargins"),
127
+ "operatingCashflow": info.get("operatingCashflow"),
128
+ "freeCashflow": info.get("freeCashflow"),
129
+ "totalCash": info.get("totalCash"),
130
+ "totalDebt": info.get("totalDebt"),
131
+ "totalCashPerShare": info.get("totalCashPerShare"),
132
+ "earningsGrowth": info.get("earningsGrowth"),
133
+ "currentRatio": info.get("currentRatio"),
134
+ "quickRatio": info.get("quickRatio"),
135
+ "returnOnAssets": info.get("returnOnAssets"),
136
+ "returnOnEquity": info.get("returnOnEquity"),
137
+ "debtToEquity": info.get("debtToEquity"),
138
+ }
139
+
140
+ return json.dumps(financial_summary, indent=2)
@@ -0,0 +1,167 @@
1
+ """Mutual funds and ETF tools for yfinance MCP server."""
2
+
3
+ import json
4
+ from typing import List
5
+
6
+ import yfinance as yf
7
+ from mcp.server import FastMCP
8
+
9
+
10
+ def register_fund_tools(mcp: FastMCP):
11
+ """Register mutual fund and ETF tools with the MCP server."""
12
+
13
+ @mcp.tool()
14
+ async def get_fund_profile(ticker: str) -> str:
15
+ """Get mutual fund or ETF profile information.
16
+
17
+ Args:
18
+ ticker: Fund ticker symbol
19
+
20
+ Returns:
21
+ JSON string containing fund profile data
22
+ """
23
+ try:
24
+ fund = yf.Ticker(ticker)
25
+ info = fund.info
26
+
27
+ fund_profile = {
28
+ "symbol": info.get("symbol"),
29
+ "longName": info.get("longName"),
30
+ "fundFamily": info.get("fundFamily"),
31
+ "category": info.get("category"),
32
+ "fundInceptionDate": info.get("fundInceptionDate"),
33
+ "totalAssets": info.get("totalAssets"),
34
+ "netExpenseRatio": info.get("annualReportExpenseRatio"),
35
+ "beta3Year": info.get("beta3Year"),
36
+ "yield": info.get("yield"),
37
+ "ytdReturn": info.get("ytdReturn"),
38
+ "threeYearAverageReturn": info.get("threeYearAverageReturn"),
39
+ "fiveYearAverageReturn": info.get("fiveYearAverageReturn"),
40
+ "morningStarRiskRating": info.get("morningStarRiskRating"),
41
+ "morningStarOverallRating": info.get("morningStarOverallRating"),
42
+ "currency": info.get("currency"),
43
+ "navPrice": info.get("navPrice"),
44
+ }
45
+
46
+ return json.dumps(fund_profile, indent=2, default=str)
47
+ except Exception as e:
48
+ return json.dumps({"error": f"Failed to get fund profile: {str(e)}"})
49
+
50
+ @mcp.tool()
51
+ async def get_fund_holdings(ticker: str, count: int = 20) -> str:
52
+ """Get fund top holdings.
53
+
54
+ Args:
55
+ ticker: Fund ticker symbol
56
+ count: Number of top holdings to return
57
+
58
+ Returns:
59
+ JSON string containing fund holdings data
60
+ """
61
+ try:
62
+ fund = yf.Ticker(ticker)
63
+
64
+ # Try to get fund holdings from info
65
+ info = fund.info
66
+ holdings = info.get("holdings", [])
67
+
68
+ if holdings:
69
+ limited_holdings = holdings[:count]
70
+ return json.dumps({"symbol": ticker, "top_holdings": limited_holdings}, indent=2)
71
+ else:
72
+ return json.dumps({"error": "No holdings data available for this fund"})
73
+ except Exception as e:
74
+ return json.dumps({"error": f"Failed to get fund holdings: {str(e)}"})
75
+
76
+ @mcp.tool()
77
+ async def get_fund_sector_allocation(ticker: str) -> str:
78
+ """Get fund sector allocation.
79
+
80
+ Args:
81
+ ticker: Fund ticker symbol
82
+
83
+ Returns:
84
+ JSON string containing sector allocation data
85
+ """
86
+ try:
87
+ fund = yf.Ticker(ticker)
88
+ info = fund.info
89
+
90
+ sector_allocation = {
91
+ "sectorWeightings": info.get("sectorWeightings", {}),
92
+ "bondRatings": info.get("bondRatings", {}),
93
+ "bondHoldings": info.get("bondHoldings", {}),
94
+ "stockHoldings": info.get("stockHoldings", {}),
95
+ }
96
+
97
+ return json.dumps(sector_allocation, indent=2)
98
+ except Exception as e:
99
+ return json.dumps({"error": f"Failed to get sector allocation: {str(e)}"})
100
+
101
+ @mcp.tool()
102
+ async def get_fund_performance(ticker: str) -> str:
103
+ """Get fund performance metrics.
104
+
105
+ Args:
106
+ ticker: Fund ticker symbol
107
+
108
+ Returns:
109
+ JSON string containing performance data
110
+ """
111
+ try:
112
+ fund = yf.Ticker(ticker)
113
+ info = fund.info
114
+
115
+ performance = {
116
+ "ytdReturn": info.get("ytdReturn"),
117
+ "oneYearReturn": info.get("oneYearReturn"),
118
+ "threeYearAverageReturn": info.get("threeYearAverageReturn"),
119
+ "fiveYearAverageReturn": info.get("fiveYearAverageReturn"),
120
+ "tenYearAverageReturn": info.get("tenYearAverageReturn"),
121
+ "alpha": info.get("alpha"),
122
+ "beta": info.get("beta"),
123
+ "rSquared": info.get("rSquared"),
124
+ "standardDeviation": info.get("standardDeviation"),
125
+ "sharpeRatio": info.get("sharpeRatio"),
126
+ "treynorRatio": info.get("treynorRatio"),
127
+ }
128
+
129
+ return json.dumps(performance, indent=2)
130
+ except Exception as e:
131
+ return json.dumps({"error": f"Failed to get fund performance: {str(e)}"})
132
+
133
+ @mcp.tool()
134
+ async def compare_funds(tickers: List[str]) -> str:
135
+ """Compare multiple funds side by side.
136
+
137
+ Args:
138
+ tickers: List of fund ticker symbols
139
+
140
+ Returns:
141
+ JSON string containing comparison data
142
+ """
143
+ try:
144
+ comparison_data = []
145
+
146
+ for ticker in tickers:
147
+ fund = yf.Ticker(ticker)
148
+ info = fund.info
149
+
150
+ fund_data = {
151
+ "symbol": ticker,
152
+ "name": info.get("longName"),
153
+ "expenseRatio": info.get("annualReportExpenseRatio"),
154
+ "yield": info.get("yield"),
155
+ "ytdReturn": info.get("ytdReturn"),
156
+ "threeYearReturn": info.get("threeYearAverageReturn"),
157
+ "fiveYearReturn": info.get("fiveYearAverageReturn"),
158
+ "totalAssets": info.get("totalAssets"),
159
+ "beta": info.get("beta"),
160
+ "morningstarRating": info.get("morningStarOverallRating"),
161
+ }
162
+
163
+ comparison_data.append(fund_data)
164
+
165
+ return json.dumps({"fund_comparison": comparison_data}, indent=2)
166
+ except Exception as e:
167
+ return json.dumps({"error": f"Failed to compare funds: {str(e)}"})