guohanghui commited on
Commit
1763c0f
·
verified ·
1 Parent(s): 6c3fc66

Update qlib/mcp_output/mcp_plugin/mcp_service.py

Browse files
qlib/mcp_output/mcp_plugin/mcp_service.py CHANGED
@@ -1,6 +1,6 @@
1
  import os
2
  import sys
3
- from typing import Union, List, Dict, Any, Tuple, Generator
4
  import pandas as pd
5
 
6
  # Path settings
@@ -26,41 +26,43 @@ mcp = FastMCP("qlib_service")
26
 
27
  @mcp.tool(name="initialize_exchange", description="Initialize and return an Exchange object for backtesting or trading simulations.")
28
  def initialize_exchange(
29
- exchange: Union[str, dict, object, os.PathLike] = None,
30
  freq: str = "day",
31
- start_time: Union[str, pd.Timestamp] = None,
32
- end_time: Union[str, pd.Timestamp] = None,
33
- codes: Union[List[str], str] = "all",
34
- subscribe_fields: List[str] = [],
35
  open_cost: float = 0.0015,
36
  close_cost: float = 0.0025,
37
  min_cost: float = 5.0,
38
- limit_threshold: Union[Tuple[str, str], float, None] = None,
39
- deal_price: Union[str, Tuple[str, str], List[str]] = None,
40
- extra_kwargs: Dict[str, Any] = None,
41
  ) -> dict:
42
  """
43
  Initialize and return an Exchange object for backtesting or trading simulations.
44
 
45
  Parameters:
46
- exchange (Union[str, dict, object, os.PathLike]): Existing exchange or configuration.
47
  freq (str): Frequency of data (e.g., 'day', 'minute').
48
- start_time (Union[str, pd.Timestamp]): Start time for the exchange.
49
- end_time (Union[str, pd.Timestamp]): End time for the exchange.
50
- codes (Union[List[str], str]): List of instruments or a string (e.g., 'all', 'csi500').
51
- subscribe_fields (List[str]): Data fields to subscribe to.
52
  open_cost (float): Open transaction cost as a ratio.
53
  close_cost (float): Close transaction cost as a ratio.
54
  min_cost (float): Minimum transaction cost.
55
- limit_threshold (Union[Tuple[str, str], float, None]): Price movement limits.
56
- deal_price (Union[str, Tuple[str, str], List[str]]): Price configuration.
57
- extra_kwargs (Dict[str, Any]): Additional keyword arguments as a dictionary.
58
 
59
  Returns:
60
  dict: A dictionary containing success, result, or error fields.
61
  """
62
  try:
63
- # Handle extra_kwargs
 
 
64
  if extra_kwargs is None:
65
  extra_kwargs = {}
66
 
@@ -78,27 +80,27 @@ def initialize_exchange(
78
  deal_price=deal_price,
79
  **extra_kwargs,
80
  )
81
- return {"success": True, "result": str(exchange_obj)}
82
  except Exception as e:
83
  return {"success": False, "error": str(e)}
84
 
85
 
86
  @mcp.tool(name="create_account", description="Create and initialize an Account instance for trading simulations.")
87
  def create_account(
88
- start_time: Union[str, pd.Timestamp],
89
- end_time: Union[str, pd.Timestamp],
90
  benchmark: str,
91
- account: Union[float, int, dict],
92
  pos_type: str = "Position",
93
  ) -> dict:
94
  """
95
  Create and initialize an Account instance for trading simulations.
96
 
97
  Parameters:
98
- start_time (Union[str, pd.Timestamp]): Start time of the benchmark.
99
- end_time (Union[str, pd.Timestamp]): End time of the benchmark.
100
  benchmark (str): Benchmark for reporting.
101
- account (Union[float, int, dict]): Initial cash and/or stock positions.
102
  pos_type (str): Type of position to use (default: "Position").
103
 
104
  Returns:
@@ -112,19 +114,19 @@ def create_account(
112
  account=account,
113
  pos_type=pos_type,
114
  )
115
- return {"success": True, "result": str(account_obj)}
116
  except Exception as e:
117
  return {"success": False, "error": str(e)}
118
 
119
 
120
  @mcp.tool(name="initialize_strategy_executor", description="Initialize and configure a trading strategy and its executor.")
121
  def initialize_strategy_executor(
122
- start_time: Union[str, pd.Timestamp],
123
- end_time: Union[str, pd.Timestamp],
124
  strategy: dict,
125
  executor: dict,
126
  benchmark: str,
127
- account: Union[float, int, dict],
128
  exchange_kwargs: dict,
129
  pos_type: str = "Position",
130
  ) -> dict:
@@ -132,12 +134,12 @@ def initialize_strategy_executor(
132
  Initialize and configure a trading strategy and its executor.
133
 
134
  Parameters:
135
- start_time (Union[str, pd.Timestamp]): Start time for the strategy.
136
- end_time (Union[str, pd.Timestamp]): End time for the strategy.
137
  strategy (dict): Strategy configuration.
138
  executor (dict): Executor configuration.
139
  benchmark (str): Benchmark identifier.
140
- account (Union[float, int, dict]): Account details.
141
  exchange_kwargs (dict): Exchange-specific settings.
142
  pos_type (str): Type of position to use (default: "Position").
143
 
@@ -155,19 +157,19 @@ def initialize_strategy_executor(
155
  exchange_kwargs=exchange_kwargs,
156
  pos_type=pos_type,
157
  )
158
- return {"success": True, "result": str(strategy_executor)}
159
  except Exception as e:
160
  return {"success": False, "error": str(e)}
161
 
162
 
163
  @mcp.tool(name="run_backtest", description="Perform a backtest to evaluate a trading strategy.")
164
  def run_backtest(
165
- start_time: Union[str, pd.Timestamp],
166
- end_time: Union[str, pd.Timestamp],
167
  strategy: dict,
168
  executor: dict,
169
  benchmark: str,
170
- account: Union[float, int, dict],
171
  exchange_kwargs: dict,
172
  pos_type: str = "Position",
173
  ) -> dict:
@@ -175,12 +177,12 @@ def run_backtest(
175
  Perform a backtest to evaluate a trading strategy.
176
 
177
  Parameters:
178
- start_time (Union[str, pd.Timestamp]): Start time for the backtest.
179
- end_time (Union[str, pd.Timestamp]): End time for the backtest.
180
  strategy (dict): Strategy configuration.
181
  executor (dict): Executor configuration.
182
  benchmark (str): Benchmark identifier.
183
- account (Union[float, int, dict]): Account details.
184
  exchange_kwargs (dict): Exchange-specific settings.
185
  pos_type (str): Type of position to use (default: "Position").
186
 
@@ -198,42 +200,41 @@ def run_backtest(
198
  exchange_kwargs=exchange_kwargs,
199
  pos_type=pos_type,
200
  )
201
- return {
202
- "success": True,
203
- "result": {
204
- "portfolio_metrics": portfolio_metrics.to_dict() if hasattr(portfolio_metrics, 'to_dict') else str(portfolio_metrics),
205
- "trading_indicators": trading_indicators.to_dict() if hasattr(trading_indicators, 'to_dict') else str(trading_indicators)
206
- }
207
  }
 
 
208
  except Exception as e:
209
  return {"success": False, "error": str(e)}
210
 
211
 
212
  @mcp.tool(name="collect_trade_data", description="Collect trade decision data for reinforcement learning training.")
213
  def collect_trade_data(
214
- start_time: Union[str, pd.Timestamp],
215
- end_time: Union[str, pd.Timestamp],
216
  strategy: dict,
217
  executor: dict,
218
  benchmark: str,
219
- account: Union[float, int, dict],
220
  exchange_kwargs: dict,
221
  pos_type: str = "Position",
222
- return_value: Any = None,
223
  ) -> dict:
224
  """
225
  Collect trade decision data for reinforcement learning training.
226
 
227
  Parameters:
228
- start_time (Union[str, pd.Timestamp]): Start time for data collection.
229
- end_time (Union[str, pd.Timestamp]): End time for data collection.
230
  strategy (dict): Strategy configuration.
231
  executor (dict): Executor configuration.
232
  benchmark (str): Benchmark identifier.
233
- account (Union[float, int, dict]): Account details.
234
  exchange_kwargs (dict): Exchange-specific settings.
235
  pos_type (str): Type of position to use (default: "Position").
236
- return_value (Any): Optional container for return values.
237
 
238
  Returns:
239
  dict: A dictionary containing success, result, or error fields.
@@ -248,28 +249,28 @@ def collect_trade_data(
248
  account=account,
249
  exchange_kwargs=exchange_kwargs,
250
  pos_type=pos_type,
251
- return_value=return_value,
252
  )
253
  data = list(data_generator)
254
- return {"success": True, "result": [str(item) for item in data]}
255
  except Exception as e:
256
  return {"success": False, "error": str(e)}
257
 
258
 
259
  @mcp.tool(name="format_trade_decisions", description="Format trade decisions into a hierarchical structure.")
260
- def format_trade_decisions(decisions: List[Any]) -> dict:
261
  """
262
  Format trade decisions into a hierarchical structure.
263
 
264
  Parameters:
265
- decisions (List[Any]): List of trade decisions.
266
 
267
  Returns:
268
  dict: A dictionary containing success, result, or error fields.
269
  """
270
  try:
271
  formatted_decisions = format_decisions(decisions)
272
- return {"success": True, "result": str(formatted_decisions)}
273
  except Exception as e:
274
  return {"success": False, "error": str(e)}
275
 
 
1
  import os
2
  import sys
3
+ from typing import Union, List, Dict, Any, Tuple, Generator, Optional
4
  import pandas as pd
5
 
6
  # Path settings
 
26
 
27
  @mcp.tool(name="initialize_exchange", description="Initialize and return an Exchange object for backtesting or trading simulations.")
28
  def initialize_exchange(
29
+ exchange: Optional[str] = None,
30
  freq: str = "day",
31
+ start_time: Optional[str] = None,
32
+ end_time: Optional[str] = None,
33
+ codes: str = "all",
34
+ subscribe_fields: Optional[List[str]] = None,
35
  open_cost: float = 0.0015,
36
  close_cost: float = 0.0025,
37
  min_cost: float = 5.0,
38
+ limit_threshold: Optional[float] = None,
39
+ deal_price: Optional[str] = None,
40
+ extra_kwargs: Optional[Dict[str, Any]] = None,
41
  ) -> dict:
42
  """
43
  Initialize and return an Exchange object for backtesting or trading simulations.
44
 
45
  Parameters:
46
+ exchange (Optional[str]): Existing exchange name or configuration.
47
  freq (str): Frequency of data (e.g., 'day', 'minute').
48
+ start_time (Optional[str]): Start time for the exchange (e.g., '2020-01-01').
49
+ end_time (Optional[str]): End time for the exchange (e.g., '2021-01-01').
50
+ codes (str): Instruments string (e.g., 'all', 'csi500').
51
+ subscribe_fields (Optional[List[str]]): Data fields to subscribe to.
52
  open_cost (float): Open transaction cost as a ratio.
53
  close_cost (float): Close transaction cost as a ratio.
54
  min_cost (float): Minimum transaction cost.
55
+ limit_threshold (Optional[float]): Price movement limits.
56
+ deal_price (Optional[str]): Price configuration.
57
+ extra_kwargs (Optional[Dict[str, Any]]): Additional keyword arguments as a dictionary.
58
 
59
  Returns:
60
  dict: A dictionary containing success, result, or error fields.
61
  """
62
  try:
63
+ # Handle None defaults
64
+ if subscribe_fields is None:
65
+ subscribe_fields = []
66
  if extra_kwargs is None:
67
  extra_kwargs = {}
68
 
 
80
  deal_price=deal_price,
81
  **extra_kwargs,
82
  )
83
+ return {"success": True, "result": str(exchange_obj), "message": "Exchange initialized successfully"}
84
  except Exception as e:
85
  return {"success": False, "error": str(e)}
86
 
87
 
88
  @mcp.tool(name="create_account", description="Create and initialize an Account instance for trading simulations.")
89
  def create_account(
90
+ start_time: str,
91
+ end_time: str,
92
  benchmark: str,
93
+ account: float,
94
  pos_type: str = "Position",
95
  ) -> dict:
96
  """
97
  Create and initialize an Account instance for trading simulations.
98
 
99
  Parameters:
100
+ start_time (str): Start time of the benchmark (e.g., '2020-01-01').
101
+ end_time (str): End time of the benchmark (e.g., '2021-01-01').
102
  benchmark (str): Benchmark for reporting.
103
+ account (float): Initial cash amount.
104
  pos_type (str): Type of position to use (default: "Position").
105
 
106
  Returns:
 
114
  account=account,
115
  pos_type=pos_type,
116
  )
117
+ return {"success": True, "result": str(account_obj), "message": "Account created successfully"}
118
  except Exception as e:
119
  return {"success": False, "error": str(e)}
120
 
121
 
122
  @mcp.tool(name="initialize_strategy_executor", description="Initialize and configure a trading strategy and its executor.")
123
  def initialize_strategy_executor(
124
+ start_time: str,
125
+ end_time: str,
126
  strategy: dict,
127
  executor: dict,
128
  benchmark: str,
129
+ account: float,
130
  exchange_kwargs: dict,
131
  pos_type: str = "Position",
132
  ) -> dict:
 
134
  Initialize and configure a trading strategy and its executor.
135
 
136
  Parameters:
137
+ start_time (str): Start time for the strategy (e.g., '2020-01-01').
138
+ end_time (str): End time for the strategy (e.g., '2021-01-01').
139
  strategy (dict): Strategy configuration.
140
  executor (dict): Executor configuration.
141
  benchmark (str): Benchmark identifier.
142
+ account (float): Initial cash amount.
143
  exchange_kwargs (dict): Exchange-specific settings.
144
  pos_type (str): Type of position to use (default: "Position").
145
 
 
157
  exchange_kwargs=exchange_kwargs,
158
  pos_type=pos_type,
159
  )
160
+ return {"success": True, "result": str(strategy_executor), "message": "Strategy executor initialized successfully"}
161
  except Exception as e:
162
  return {"success": False, "error": str(e)}
163
 
164
 
165
  @mcp.tool(name="run_backtest", description="Perform a backtest to evaluate a trading strategy.")
166
  def run_backtest(
167
+ start_time: str,
168
+ end_time: str,
169
  strategy: dict,
170
  executor: dict,
171
  benchmark: str,
172
+ account: float,
173
  exchange_kwargs: dict,
174
  pos_type: str = "Position",
175
  ) -> dict:
 
177
  Perform a backtest to evaluate a trading strategy.
178
 
179
  Parameters:
180
+ start_time (str): Start time for the backtest (e.g., '2020-01-01').
181
+ end_time (str): End time for the backtest (e.g., '2021-01-01').
182
  strategy (dict): Strategy configuration.
183
  executor (dict): Executor configuration.
184
  benchmark (str): Benchmark identifier.
185
+ account (float): Initial cash amount.
186
  exchange_kwargs (dict): Exchange-specific settings.
187
  pos_type (str): Type of position to use (default: "Position").
188
 
 
200
  exchange_kwargs=exchange_kwargs,
201
  pos_type=pos_type,
202
  )
203
+
204
+ # Convert to serializable format
205
+ result = {
206
+ "portfolio_metrics": portfolio_metrics.to_dict() if hasattr(portfolio_metrics, 'to_dict') else str(portfolio_metrics),
207
+ "trading_indicators": trading_indicators.to_dict() if hasattr(trading_indicators, 'to_dict') else str(trading_indicators)
 
208
  }
209
+
210
+ return {"success": True, "result": result, "message": "Backtest completed successfully"}
211
  except Exception as e:
212
  return {"success": False, "error": str(e)}
213
 
214
 
215
  @mcp.tool(name="collect_trade_data", description="Collect trade decision data for reinforcement learning training.")
216
  def collect_trade_data(
217
+ start_time: str,
218
+ end_time: str,
219
  strategy: dict,
220
  executor: dict,
221
  benchmark: str,
222
+ account: float,
223
  exchange_kwargs: dict,
224
  pos_type: str = "Position",
 
225
  ) -> dict:
226
  """
227
  Collect trade decision data for reinforcement learning training.
228
 
229
  Parameters:
230
+ start_time (str): Start time for data collection (e.g., '2020-01-01').
231
+ end_time (str): End time for data collection (e.g., '2021-01-01').
232
  strategy (dict): Strategy configuration.
233
  executor (dict): Executor configuration.
234
  benchmark (str): Benchmark identifier.
235
+ account (float): Initial cash amount.
236
  exchange_kwargs (dict): Exchange-specific settings.
237
  pos_type (str): Type of position to use (default: "Position").
 
238
 
239
  Returns:
240
  dict: A dictionary containing success, result, or error fields.
 
249
  account=account,
250
  exchange_kwargs=exchange_kwargs,
251
  pos_type=pos_type,
252
+ return_value=None,
253
  )
254
  data = list(data_generator)
255
+ return {"success": True, "result": [str(item) for item in data], "message": "Trade data collected successfully"}
256
  except Exception as e:
257
  return {"success": False, "error": str(e)}
258
 
259
 
260
  @mcp.tool(name="format_trade_decisions", description="Format trade decisions into a hierarchical structure.")
261
+ def format_trade_decisions(decisions: List[str]) -> dict:
262
  """
263
  Format trade decisions into a hierarchical structure.
264
 
265
  Parameters:
266
+ decisions (List[str]): List of trade decisions as strings.
267
 
268
  Returns:
269
  dict: A dictionary containing success, result, or error fields.
270
  """
271
  try:
272
  formatted_decisions = format_decisions(decisions)
273
+ return {"success": True, "result": str(formatted_decisions), "message": "Decisions formatted successfully"}
274
  except Exception as e:
275
  return {"success": False, "error": str(e)}
276