Skip to main content
Glama
liuguoping1024

SWLC MCP Server

backtest_lottery

Evaluate prediction algorithm accuracy for lottery games by testing historical data with configurable training windows and step sizes.

Instructions

回测预测算法,评估预测准确性

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
lottery_typeYes彩票类型
window_sizeNo窗口大小(训练数据期数)
stepNo步长(每次移动的期数)

Implementation Reference

  • MCP tool handler for 'backtest_lottery': fetches historical lottery data, converts to dict format, calls BacktestEngine.run_backtest, and formats the summary results for output.
    elif name == "backtest_lottery":
        lottery_type = arguments.get("lottery_type")
        window_size = arguments.get("window_size", 100)
        step = arguments.get("step", 50)
        
        try:
            # 获取历史数据用于回测
            historical_data = await lottery_service.get_historical_data(lottery_type, window_size * 2)
            if len(historical_data) < window_size:
                return [types.TextContent(type="text", text=f"历史数据不足,需要至少{window_size}期数据")]
            
            # 转换为字典格式
            history_dict = [{
                'period': r.period,
                'numbers': r.numbers,
                'special_numbers': r.special_numbers,
                'draw_date': r.draw_date
            } for r in historical_data]
            
            # 执行回测
            backtest_result = await lottery_service.backtest_engine.run_backtest(
                lottery_type, history_dict, window_size=window_size, step=step
            )
            
            text_lines = [
                f"{lottery_type}回测结果:\n",
                f"总回测期数:{backtest_result.total_periods}期",
                f"平均准确率:{backtest_result.average_accuracy:.2%}",
                f"最佳策略:{backtest_result.best_strategy}",
                "\n各策略表现:"
            ]
            
            for strategy, performance in backtest_result.strategy_performance.items():
                text_lines.append(f"- {strategy}: 准确率 {performance:.2%}")
            
            return [types.TextContent(type="text", text="\n".join(text_lines))]
            
        except Exception as e:
            logger.error(f"回测失败: {e}")
            return [types.TextContent(type="text", text=f"回测失败:{str(e)}")]
  • Input schema for the backtest_lottery tool, defining parameters: lottery_type (required, enum), window_size (default 100), step (default 50).
        name="backtest_lottery",
        description="回测预测算法,评估预测准确性",
        inputSchema={
            "type": "object",
            "properties": {
                "lottery_type": {
                    "type": "string",
                    "enum": ["双色球", "福彩3D", "七乐彩", "快乐8"],
                    "description": "彩票类型"
                },
                "window_size": {
                    "type": "integer",
                    "minimum": 50,
                    "maximum": 500,
                    "default": 100,
                    "description": "窗口大小(训练数据期数)"
                },
                "step": {
                    "type": "integer",
                    "minimum": 10,
                    "maximum": 100,
                    "default": 50,
                    "description": "步长(每次移动的期数)"
                }
            },
            "required": ["lottery_type"]
        }
    )
  • Core implementation of backtesting in BacktestEngine.run_backtest: uses sliding window on historical data, generates predictions via PredictionManager for each window, calculates accuracy, aggregates results into BacktestSummary.
    async def run_backtest(self, lottery_type: str, historical_data: List[Dict], 
                          window_size: int = 100, step: int = 50) -> BacktestSummary:
        """运行回测"""
        try:
            if len(historical_data) < window_size:
                raise ValueError(f"历史数据不足,需要至少{window_size}期数据")
            
            results = []
            chart_data = {
                'periods': [],
                'accuracy': [],
                'precision': []
            }
            
            # 滑动窗口回测
            for start_idx in range(0, len(historical_data) - window_size, step):
                end_idx = start_idx + window_size
                test_period = start_idx + window_size
                
                if test_period >= len(historical_data):
                    break
                
                # 训练数据(历史数据)
                train_data = historical_data[start_idx:end_idx]
                # 测试数据(目标期)
                test_data = historical_data[test_period]
                
                # 为每个方法生成预测
                method_results = {}
                for method in self.methods:
                    try:
                        predictions = await self.prediction_manager.predict(
                            lottery_type, train_data, method=method, count=5
                        )
                        
                        # 计算预测准确性
                        accuracy = self._calculate_prediction_accuracy(
                            predictions, test_data, lottery_type
                        )
                        
                        method_results[method] = {
                            'predictions': predictions,
                            'accuracy': accuracy
                        }
                        
                    except Exception as e:
                        logger.error(f"方法{method}预测失败: {e}")
                        method_results[method] = {
                            'predictions': [],
                            'accuracy': 0.0
                        }
                
                # 记录结果
                period_result = BacktestResult(
                    period=test_data.get('period', f'Period_{test_period}'),
                    actual_numbers=test_data.get('numbers', []),
                    actual_special_numbers=test_data.get('special_numbers'),
                    predictions=method_results,
                    accuracy=max([r['accuracy'] for r in method_results.values()]),
                    method=max(method_results.items(), key=lambda x: x[1]['accuracy'])[0]
                )
                
                results.append(period_result)
                
                # 更新图表数据
                chart_data['periods'].append(period_result.period)
                chart_data['accuracy'].append(period_result.accuracy)
                chart_data['precision'].append(self._calculate_precision(method_results))
            
            # 生成摘要
            summary = self._generate_summary(results, chart_data)
            
            return summary
            
        except Exception as e:
            logger.error(f"回测失败: {e}")
            raise
  • Registration of the backtest_lottery tool in the MCP server's list_tools() method, which returns the list of available tools including this one.
    @server.list_tools()
    async def list_tools() -> List[types.Tool]:
        """列出所有可用工具"""
        return [
            types.Tool(
                name="get_latest_ssq",
                description="获取双色球最新开奖结果",
                inputSchema={
                    "type": "object",
                    "properties": {},
                    "required": []
                }
            ),
            types.Tool(
                name="get_latest_3d",
                description="获取福彩3D最新开奖结果",
                inputSchema={
                    "type": "object",
                    "properties": {},
                    "required": []
                }
            ),
            types.Tool(
                name="get_latest_qlc", 
                description="获取七乐彩最新开奖结果",
                inputSchema={
                    "type": "object",
                    "properties": {},
                    "required": []
                }
            ),
            types.Tool(
                name="get_latest_kl8",
                description="获取快乐8最新开奖结果",
                inputSchema={
                    "type": "object",
                    "properties": {},
                    "required": []
                }
            ),
            types.Tool(
                name="get_historical_data",
                description="获取指定彩票类型的历史开奖数据",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "lottery_type": {
                            "type": "string",
                            "enum": ["双色球", "福彩3D", "七乐彩", "快乐8"],
                            "description": "彩票类型"
                        },
                        "periods": {
                            "type": "integer",
                            "minimum": 1,
                            "maximum": 1000,
                            "default": 10,
                            "description": "获取期数"
                        }
                    },
                    "required": ["lottery_type"]
                }
            ),
            types.Tool(
                name="analyze_numbers",
                description="分析彩票号码统计信息,包括热号、冷号等",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "lottery_type": {
                            "type": "string", 
                            "enum": ["双色球", "福彩3D", "七乐彩", "快乐8"],
                            "description": "彩票类型"
                        },
                        "periods": {
                            "type": "integer",
                            "minimum": 5,
                            "maximum": 1000,
                            "default": 30,
                            "description": "分析期数"
                        }
                    },
                    "required": ["lottery_type"]
                }
            ),
            types.Tool(
                name="analyze_seq_numbers",
                description="分析号码连续出现概率(滑窗),返回理论值与实测值",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "lottery_type": {
                            "type": "string",
                            "enum": ["双色球", "福彩3D", "七乐彩", "快乐8"],
                            "description": "彩票类型"
                        },
                        "periods": {
                            "type": "integer",
                            "minimum": 5,
                            "maximum": 1000,
                            "default": 100,
                            "description": "分析期数"
                        },
                        "sequence_length": {
                            "type": "integer",
                            "minimum": 1,
                            "maximum": 10,
                            "default": 2,
                            "description": "连续期数"
                        }
                    },
                    "required": ["lottery_type"]
                }
            ),
            types.Tool(
                name="generate_random_numbers",
                description="生成随机彩票号码推荐",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "lottery_type": {
                            "type": "string",
                            "enum": ["双色球", "福彩3D", "七乐彩", "快乐8"],
                            "description": "彩票类型"
                        },
                        "count": {
                            "type": "integer",
                            "minimum": 1,
                            "maximum": 10,
                            "default": 1,
                            "description": "生成组数"
                        }
                    },
                    "required": ["lottery_type"]
                }
            ),
            types.Tool(
                name="sync_lottery_data",
                description="同步指定彩票类型的最新数据到本地数据库",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "lottery_type": {
                            "type": "string",
                            "enum": ["双色球", "福彩3D", "七乐彩", "快乐8"],
                            "description": "彩票类型"
                        },
                        "periods": {
                            "type": "integer",
                            "minimum": 1,
                            "maximum": 50,
                            "default": 10,
                            "description": "同步期数"
                        }
                    },
                    "required": ["lottery_type"]
                }
            ),
            types.Tool(
                name="force_sync_data",
                description="强制同步指定彩票类型的最新数据到本地数据库",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "lottery_type": {
                            "type": "string",
                            "enum": ["双色球", "福彩3D", "七乐彩", "快乐8"],
                            "description": "彩票类型"
                        },
                        "periods": {
                            "type": "integer",
                            "minimum": 1,
                            "maximum": 1000,
                            "default": 20,
                            "description": "同步期数"
                        }
                    },
                    "required": ["lottery_type"]
                }
            ),
            types.Tool(
                name="get_database_info",
                description="获取本地数据库统计信息",
                inputSchema={
                    "type": "object",
                    "properties": {},
                    "required": []
                }
            ),
            types.Tool(
                name="predict_lottery",
                description="预测彩票号码,基于历史数据生成预测结果",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "lottery_type": {
                            "type": "string",
                            "enum": ["双色球", "福彩3D", "七乐彩", "快乐8"],
                            "description": "彩票类型"
                        },
                        "method": {
                            "type": "string",
                            "enum": ["rule"],
                            "default": "rule",
                            "description": "预测方法"
                        },
                        "count": {
                            "type": "integer",
                            "minimum": 1,
                            "maximum": 20,
                            "default": 5,
                            "description": "预测组数"
                        },
                        "strategy": {
                            "type": "string",
                            "enum": ["all", "balanced", "cold_recovery", "hot_focus", "interval_balance", "contrarian"],
                            "default": "all",
                            "description": "预测策略"
                        }
                    },
                    "required": ["lottery_type"]
                }
            ),
            types.Tool(
                name="backtest_lottery",
                description="回测预测算法,评估预测准确性",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "lottery_type": {
                            "type": "string",
                            "enum": ["双色球", "福彩3D", "七乐彩", "快乐8"],
                            "description": "彩票类型"
                        },
                        "window_size": {
                            "type": "integer",
                            "minimum": 50,
                            "maximum": 500,
                            "default": 100,
                            "description": "窗口大小(训练数据期数)"
                        },
                        "step": {
                            "type": "integer",
                            "minimum": 10,
                            "maximum": 100,
                            "default": 50,
                            "description": "步长(每次移动的期数)"
                        }
                    },
                    "required": ["lottery_type"]
                }
            )
        ]
  • PredictionManager.predict method used by backtest to generate predictions for accuracy calculation; delegates to RuleBasedPredictor.
    async def predict(self, lottery_type: str, historical_data: List[Dict], 
                     method: str = 'rule', count: int = 5, strategy: Optional[str] = None) -> List[PredictionResult]:
        """执行预测"""
        try:
            # 目前仅实现规则+策略
            return self.rule_predictor.predict(lottery_type, historical_data, count=count, strategy=strategy)
        except Exception as e:
            logger.error(f"预测失败: {e}")
            return self.rule_predictor.predict(lottery_type, historical_data, count=count, strategy=strategy)

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/liuguoping1024/swlc-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server