<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>个股指数对比分析</title>
    <!-- 引入 ECharts -->
    <script src="../static/js/echarts.min.js"></script>
    <style>
        .container {
            padding: 20px;
            font-family: Arial, sans-serif;
        }
        .input-group {
            margin-bottom: 20px;
        }
        .input-group label {
            display: inline-block;
            width: 100px;
            margin-right: 10px;
        }
        .input-group input, .input-group select {
            padding: 5px;
            margin-right: 10px;
        }
        .result-panel {
            background-color: #f5f5f5;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .strength-indicator {
            font-size: 24px;
            font-weight: bold;
            color: #ff4d4f;
        }
        .charts-container {
            display: flex;
            gap: 20px;
        }
        .chart-item {
            flex: 1;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>个股指数对比分析</h1>
        
        <!-- 输入控制区 -->
        <div class="input-group">
            <label>个股代码:</label>
            <input type="text" id="stockCode" placeholder="输入股票代码">
        </div>
        
        <div class="input-group">
            <label>对比指数:</label>
            <select id="indexSelect">
                <option value="000001|1">000001 - 上证指数</option>
                <option value="399001|0">399001 - 深证成指</option>
                <option value="399006|0">399006 - 创业板指</option>
                <option value="000688|1">000688 - 科创50指数</option>
            </select>
        </div>
        
        <div class="input-group">
            <button onclick="fetchAndAnalyze()" style="padding: 10px 20px; background-color: #1890ff; color: white; border: none; border-radius: 4px; cursor: pointer;">开始分析</button>
        </div>

        <!-- 结果展示区 -->
        <div class="result-panel" id="resultPanel" style="display: none;">
            <h3>逆市强度分析结果</h3>
            <div>
                <span>逆市强度: </span>
                <span class="strength-indicator" id="strengthValue">-</span>
            </div>
            <div style="margin-top: 10px; font-size: 14px; color: #666;">
                指数弱势次数: <span id="indexWeakCount">-</span> | 
                个股逆市次数: <span id="stockStrongCount">-</span>
            </div>
        </div>

        <!-- 图表展示区 -->
        <div class="charts-container">
            <div class="chart-item">
                <h3>个股买卖方能量</h3>
                <div id="stockChart" style="width: 100%; height: 400px;"></div>
            </div>
            <div class="chart-item">
                <h3>指数买卖方能量</h3>
                <div id="indexChart" style="width: 100%; height: 400px;"></div>
            </div>
        </div>
    </div>

    <script>
        // 初始化图表
        var stockChart = echarts.init(document.getElementById('stockChart'));
        var indexChart = echarts.init(document.getElementById('indexChart'));

        // 获取分时数据
        async function fetchStockData(code, market) {
            var baseUrl = "http://push2ex.eastmoney.com/getStockFenShi?pagesize=6000&ut=7eea3edcaed734bea9cbfc24409ed989&dpt=wzfscj&pageindex=0&id=3007792&sort=1&ft=1&code=REPLACE_CODE&market=REPLACE_MARKET";
            var url = baseUrl.replace("REPLACE_CODE", code).replace("REPLACE_MARKET", market);
            
            try {
                const response = await fetch(url);
                const jsonData = await response.json();
                return jsonData.data.data;
            } catch (error) {
                console.log('Request failed for ' + code, error);
                return null;
            }
        }3

        // 处理数据：按分钟聚合买卖方数据
        function processTradeData(data) {
            var buyData = {};
            var sellData = {};
            
            if (!data) return { buyData, sellData };
            
            data.forEach(function(item) {
                var minute = Math.floor(item.t / 100);
                
                if (item.bs === 1) {
                    // 卖方
                    if (!sellData[minute]) sellData[minute] = 0;
                    sellData[minute] += item.v;
                } else if (item.bs === 2) {
                    // 买方
                    if (!buyData[minute]) buyData[minute] = 0;
                    buyData[minute] += item.v;
                }
            });
            
            return { buyData, sellData };
        }

        // 计算逆市强度
        function calculateCounterTrendStrength(stockBuyData, stockSellData, indexBuyData, indexSellData) {
            var indexWeakCount = 0;  // 指数弱势次数（卖方 > 买方）
            var stockStrongCount = 0; // 个股逆市强势次数
            
            // 获取所有时间点
            var allMinutes = new Set([
                ...Object.keys(stockBuyData), 
                ...Object.keys(stockSellData),
                ...Object.keys(indexBuyData), 
                ...Object.keys(indexSellData)
            ]);
            
            allMinutes.forEach(function(minute) {
                var stockBuy = stockBuyData[minute] || 0;
                var stockSell = stockSellData[minute] || 0;
                var indexBuy = indexBuyData[minute] || 0;
                var indexSell = indexSellData[minute] || 0;
                
                // 指数弱势：卖方量 > 买方量
                if (indexSell > indexBuy) {
                    indexWeakCount++;
                    
                    // 个股强势：买方量 > 卖方量
                    if (stockBuy > stockSell) {
                        stockStrongCount++;
                    }
                }
            });
            
            var strength = indexWeakCount > 0 ? (stockStrongCount / indexWeakCount * 100) : 0;
            
            return {
                strength: strength,
                indexWeakCount: indexWeakCount,
                stockStrongCount: stockStrongCount
            };
        }

        // 生成图表配置
        function generateChartOption(buyData, sellData, title) {
            var allMinutes = new Set([...Object.keys(buyData), ...Object.keys(sellData)]);
            var sortedMinutes = Array.from(allMinutes).map(Number).sort((a, b) => a - b);
            
            var categories = [];
            var buyValues = [];
            var sellValues = [];
            
            sortedMinutes.forEach(function(minute) {
                var timeStr = minute.toString().padStart(6, '0');
                var formattedTime = timeStr.substring(0,2) + ':' + timeStr.substring(2,4) + ':' + timeStr.substring(4,6);
                categories.push(formattedTime);
                buyValues.push(buyData[minute] || 0);
                sellValues.push(sellData[minute] || 0);
            });

            return {
                title: {
                    text: title
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    data: ['买方', '卖方']
                },
                xAxis: {
                    data: categories,
                    axisLabel: {
                        rotate: 45
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '交易量'
                },
                series: [{
                    name: '买方',
                    type: 'bar',
                    data: buyValues,
                    stack: '总量',
                    itemStyle: {
                        color: '#ff4d4f'
                    }
                }, {
                    name: '卖方',
                    type: 'bar',
                    data: sellValues,
                    stack: '总量',
                    itemStyle: {
                        color: '#52c41a'
                    }
                }],
                dataZoom: [{
                    type: 'inside',
                    start: 0,
                    end: 100
                }, {
                    type: 'slider',
                    start: 0,
                    end: 100
                }]
            };
        }

        // 主分析函数
        async function fetchAndAnalyze() {
            var stockCode = document.getElementById('stockCode').value;
            var indexInfo = document.getElementById('indexSelect').value.split('|');
            var indexCode = indexInfo[0];
            var indexMarket = indexInfo[1];
            
            if (!stockCode) {
                alert('请输入股票代码');
                return;
            }

            // 确定个股市场
            var stockMarket = stockCode.startsWith('6') ? '1' : '0';
            
            console.log('开始获取数据...');
            console.log('个股:', stockCode, '市场:', stockMarket);
            console.log('指数:', indexCode, '市场:', indexMarket);

            try {
                // 并行获取个股和指数数据
                const [stockData, indexData] = await Promise.all([
                    fetchStockData(stockCode, stockMarket),
                    fetchStockData(indexCode, indexMarket)
                ]);

                if (!stockData || !indexData) {
                    alert('数据获取失败，请检查代码是否正确');
                    return;
                }

                // 处理数据
                var stockResult = processTradeData(stockData);
                var indexResult = processTradeData(indexData);

                // 计算逆市强度
                var analysis = calculateCounterTrendStrength(
                    stockResult.buyData, 
                    stockResult.sellData,
                    indexResult.buyData, 
                    indexResult.sellData
                );

                // 显示结果
                document.getElementById('resultPanel').style.display = 'block';
                document.getElementById('strengthValue').textContent = analysis.strength.toFixed(2) + '%';
                document.getElementById('indexWeakCount').textContent = analysis.indexWeakCount;
                document.getElementById('stockStrongCount').textContent = analysis.stockStrongCount;

                // 生成图表
                var stockOption = generateChartOption(stockResult.buyData, stockResult.sellData, '个股: ' + stockCode);
                var indexOption = generateChartOption(indexResult.buyData, indexResult.sellData, '指数: ' + indexCode);

                stockChart.setOption(stockOption);
                indexChart.setOption(indexOption);

                console.log('分析完成');
                console.log('逆市强度:', analysis.strength.toFixed(2) + '%');

            } catch (error) {
                console.error('分析过程中出现错误:', error);
                alert('分析过程中出现错误，请重试');
            }
        }
    </script>
</body>
</html> 