openclawversion unknown

stock-forecast

QiangQiang233@QiangQiang233⭐ 0 stars· last commit 8mo ago· 0 open issues

OpenClaw Skill - stock-forecast

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

7.0/10
Verified
Mar 25, 2026

// RATINGS

⭐GitHub Stars
⭐ 0 on GitHubGitHub ↗

New / niche

🟢ProSkills ScoreAI Verified
7.0/10
📍

Not yet listed on ClawHub or SkillsMP

// README

README not available

View on GitHub

// HOW IT'S BUILT

// FILES

5 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • SKILL.md10 KBb100a7fd9aa1upstream ↗
    ---
    name: stock-forecast
    description: A股股价走势预估工具,结合技术面+消息面(六大维度)+自动获取市场环境
    metadata:
      {
        "openclaw": {
          "requires": {
            "bins": ["python3"],
            "python_modules": ["requests", "statistics"]
          },
          "install": [
            {
              "id": "pip",
              "kind": "pip",
              "package": "requests"
            }
          ],
          "trigger": ["股价预估", "股票分析", "走势预测", "多周期", "分析股票", "预估"]
        }
      }
    ---
    
    # 股价走势预估 Skill
    
    ## 简介
    
    基于历史数据、技术指标、宏观环境、行业动态、公司消息,综合分析并预估A股股价未来走势。支持次日、7日、30日多周期预估。
    
    ## 核心功能
    
    ### 1. 技术面分析
    
    使用 **akshare-stock** 获取数据,计算以下指标:
    
    | 指标类型 | 指标名称 | 说明 |
    |----------|----------|------|
    | 均线 | MA5/MA10/MA20/MA60 | 判断趋势方向 |
    | 趋势 | 上涨/下跌/震荡 | MA排列状态 |
    | 支撑/压力 | 支撑位、压力位 | 价格上下限 |
    | 量能 | 量比、成交量 | 放量/缩量 |
    | RSI | 相对强弱指数 | 超买超卖(14日) |
    | MACD | 指数平滑异同移动平均线 | 金叉/死叉 |
    | 布林带 | Bollinger Bands | 上下轨突破 |
    
    ### 2. 消息面分析(六大维度)
    
    **重要:每个维度都必须主动分析,不可遗漏!**
    
    #### 维度1:宏观经济与政策面
    - 货币政策:降准、降息、LPR调整
    - 财政政策:政府债券、专项债、减税降费
    - 经济数据:GDP、CPI、PPI、PMI、社融
    - 高层会议:政治局、两会、部委发布会
    
    **关键词**:央行宽松、适度宽松、财政刺激、新质生产力、内需
    
    #### 维度2:行业与产业动态
    - 产业政策:补贴、反垄断、环保限产
    - 供需关系:原材料价格、产能
    - 技术突破:AI、固态电池、6G
    - 行业展会:车展、MWC、药交会
    
    **关键词**:新能源车补贴、医药集采、芯片涨价、油价、金价
    
    #### 维度3:公司微观层面
    - 定期报告:年报、季报营收/利润
    - 重大事项:并购重组、增持回购、合同订单
    - 管理层变动
    - 分红送转
    
    **关键词**:业绩预增、大单、回购、股权激励、分红
    
    #### 维度4:地缘政治与国际局势
    - 贸易摩擦:关税、出口管制
    - 战争与冲突:中东、东欧
    - 外交关系:合作/制裁
    
    **关键词**:中美关税、中东局势、油价上涨、黄金避险
    
    **必须分析**:
    - 中东冲突 → 油价 → 大宗商品/原材料成本
    - 俄乌冲突 → 天然气/金属价格
    - 中美关系 → 出口/供应链
    
    #### 维度5:市场资金与情绪面
    - 主力资金流向:北向资金、机构席位
    - 融资融券数据
    - 舆情与传闻
    - 指数纳入/剔除
    
    **关键词**:北向资金、融资买入、社保重仓、外资流出
    
    #### 维度6:突发事件
    - 自然灾害
    - 公共卫生事件
    - 安全事故
    
    **关键词**:黑天鹅、突发事件
    
    ### 3. 智能概念库
    
    - 预置股票概念(特斯拉概念、机器人概念等)
    - 支持用户补充新概念
    - 自动学习保存到本地知识库
    
    ### 4. 主动学习与自主判断
    
    **工作流程**:
    1. **收到股票代码** → 自动识别相关概念
    2. **多维度搜索** → 搜索股票名称 + 相关概念 + 行业动态
    3. **综合分析** → 不是被动接收用户输入,而是主动输出判断
    4. **验证更新** → 发现新的重要信息,主动更新到概念库
    5. **不确定时** → 主动询问用户确认
    
    **原则**:
    - 不完全依赖用户提供的信息
    - 用户说的不一定是正确的,需要自己验证
    - 主动搜索比被动等待更可靠
    - 发现新热点概念,主动添加到知识库
    
    ### 5. 多周期预估
    
    | 周期 | 技术面权重 | 消息面权重 | 影响因素 |
    |------|------------|------------|----------|
    | 次日 | 60% | 40% | 技术面当日 + 消息面 |
    | 7日 | 50% | 50% | MA10趋势 + 消息面 |
    | 30日 | 40% | 60% | MA20趋势 + 消息面 |
    
    ## 评分体系
    
    | 条件 | 分数 |
    |------|------|
    | 价格 > MA5 | +1 |
    | 价格 > MA10 | +1 |
    | MA5 > MA10(金叉) | +2 |
    | MA10 < MA20(死叉) | -2 |
    | RSI > 70(超买) | -1 |
    | RSI < 30(超卖) | +1 |
    | 消息面偏多 | +2 |
    | 消息面偏空 | -2 |
    
    ### 预估判定
    
    | 总分 | 预估结果 | 概率 |
    |------|----------|------|
    | >=3 | 上涨 | 70% |
    | >=1 | 震荡偏多 | 60% |
    | >=-1 | 震荡 | 50% |
    | >=-3 | 震荡偏空 | 40% |
    | <-3 | 下跌 | 30% |
    
    ## 数据来源
    
    ### 主要数据源 - 必须优先使用
    
    **akshare-stock** - 用于获取:
    - A股实时行情
    - 历史K线数据(日K/周K/月K)
    - 财务数据(营收、利润、负债率)
    - 板块信息
    - 资金流向(北向资金、融资融券)
    
    **china-stock-analysis** - 用于获取:
    - 公司基本面分析
    - 估值数据(PE、PB、PS)
    - 财务健康状况
    - 内在价值评估
    - 行业对比
    
    ### 辅助数据源 - 备用
    
    当主数据源不可用时,使用以下接口:
    
    | 用途 | 接口 | URL |
    |------|------|-----|
    | 实时行情 | 腾讯财经 | `https://qt.gtimg.cn/q=sz002050` |
    | K线历史 | 腾讯财经 | `https://web.ifzq.gtimg.cn/appstock/app/fqkline/get` |
    | 新闻搜索 | 东方财富 | `https://search-api-web.eastmoney.com/search/jsonp` |
    
    ### 新闻数据
    
    通过东方财富搜索API获取:
    - 公司新闻
    - 行业动态
    - 宏观经济新闻
    - 地缘政治相关
    
    ---
    
    ## ⚠️ 数据校验规范(重要)
    
    **为防止数据混淆和误读,必须遵守以下规范:**
    
    ### 1. 股票身份验证
    
    获取任何数据前,**必须先验证股票名称和代码匹配**:
    
    ```
    输入:用户查询"XXX股票"
    第一步:获取股票基本信息(名称、代码、交易所)
    第二步:验证名称/代码与输入匹配
    第三步:若不匹配,提示用户确认
    第四步:确认后才进行后续分析
    ```
    
    ### 2. 关键指标交叉验证
    
    **以下指标必须和新闻/公告交叉验证**:
    
    | 指标 | 验证方法 |
    |------|----------|
    | 净利润 | 与年报/季报公告对比 |
    | 营收 | 与年报/季报公告对比 |
    | EPS | 净利润÷股本,验证合理性 |
    | 分红 | 与公司公告对比 |
    | 重大合同 | 与公司公告对比 |
    
    ### 3. 指标合理性检查
    
    | 指标 | 正常范围 | 异常预警 |
    |------|----------|----------|
    | PE(TTM) | 5-100 | >1000 需复核 |
    | ROE | 5%-30% | >50% 需复核 |
    | 毛利率 | 行业均值±20% | 偏离过大需复核 |
    | 资产负债率 | 20%-70% | >90% 需复核 |
    
    ### 4. 数据来源标注
    
    **每次输出必须标注**:
    
    ```
    数据来源:akshare-stock
    获取时间:2026-03-25 00:40
    数据时效:盘中为实时,盘后为上一交易日
    ```
    
    ### 5. 异常处理
    
    - 若数据源返回空值/NaN,标注"数据不可用"
    - 若交叉验证不一致,标注"数据存疑,需进一步核实"
    - 若指标超出正常范围,用⚠️标注提醒复核
    
    ## 智能概念库工作流
    
    收到股票代码后:
    1. **识别相关概念**:义乌、外贸、退税商店、跨境电商等
    2. **多维度搜索**:
       - 搜"股票名称"
       - 搜"相关概念"(如"义乌"、"退税"、"外贸")
       - 搜"行业动态"
    3. **综合分析**:结合所有相关新闻判断影响
    
    ## 使用方法
    
    ### 基础分析
    ```
    分析紫金矿业601899
    预估三花智控002050未来走势
    ```
    
    ### 带消息面
    ```
    分析光迅科技,AI算力需求旺盛,业绩预增
    ```
    
    ## 输出示例
    
    ```
    =================================================================
           三花智控(002050) 综合分析
    =================================================================
    
    【技术面】
    当前价格: 42.57元 | 昨收: 43.00元 | 涨跌: -1.00%
    
    均线系统:
      MA5: 44.37 | MA10: 45.99 | MA20: 45.87 | MA60: 43.52
      状态: 下跌(空头排列)
    
    技术指标:
      RSI(14): 28.5(超卖区域)
      MACD: DIF=-1.23, DEA=-0.87, BAR=-0.36(死叉)
      布林带: 上轨46.20 中轨44.50 下轨42.80
    
    支撑位: 42.80 | 压力位: 44.50
    成交量: 95.9万(较前日萎缩,量比0.82)
    
    【估值分析】(来自china-stock-analysis)
      PE(TTM): 28.5 | PB: 4.2 | PS: 3.1
      行业平均PE: 32.0 | 相对低估: 是
    
    【消息面】六大维度分析:
    
    | 维度 | 状态 | 说明 |
    |------|------|------|
    | 宏观 | ⚠️ | 市场整体回调 |
    | 行业 | ✅ | 热管理/机器人赛道景气 |
    | 公司 | ✅ | 业绩增长31%,分红10派2.8 |
    | 地缘 | ⚠️ | 中东冲突 → 油价波动风险 |
    | 市场资金 | ⚠️ | 融资净偿还8214万 |
    | 突发事件 | - | 无 |
    
    利好: 业绩增长、分红、基本面优秀
    利空: 股价大跌、市值蒸发500亿
    
    =================================================================
                        多周期预估结果
    =================================================================
    
    📅 次日: 震荡偏多
       理由: 技术超卖(RSI=28.5) + 业绩支撑
       预估区间: 41.50~44.00元
    
    📆 7日: 震荡
       理由: 等待MA10企稳,消息面观望
       预估区间: 42.00~45.50元
    
    📆 30日: 待观察
       理由: 取决于市场情绪和中东局势
       预估区间: 40.00~48.00元
    
    =================================================================
    综合评分: -1(技术面偏空,但估值偏低支撑)
    =================================================================
    ⚠️ 仅供参考,不构成投资建议
    =================================================================
    ```
    
    ## 注意事项
    
    1. 预估仅作参考:股市有风险
    2. 消息面影响随时间递减
    3. **六大维度必须完整分析,不可遗漏地缘政治**
    4. **数据源必须优先使用akshare-stock和china-stock-analysis**
    5. **必须主动搜索相关概念**,而非仅搜索股票名称
    6. 只有当主数据源不可用时,才使用辅助接口
    7. RSI<30视为超卖,RSI>70视为超买
    8. **必须进行股票身份验证,防止数据混淆**
    9. **关键指标必须交叉验证,防止误读**
    
    ## 更新日志
    
    - v2.2.0 (2026-03-25): 增加数据校验规范,防止数据混淆和误读
    - v2.1.0 (2026-03-25): 增加RSI/MACD/布林带指标,优化输出示例,修复重复内容
    - v2.0.0 (2026-03-24): 增加六大维度分析,自动获取市场环境,智能概念库
    - v1.0.0 (2026-03-23): 初始版本
    
  • stock_forecast.py9.6 KB1786e543dec6upstream ↗
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    股价走势预估工具
    结合技术面 + 消息面 进行综合分析
    """
    
    import json
    import os
    import re
    import statistics
    import sys
    
    try:
        import requests
    except ImportError:
        print("Error: requests module not installed")
        print("Please install: pip install requests")
        sys.exit(1)
    
    
    class StockAnalyzer:
        """股票走势预估分析器"""
        
        def __init__(self, symbol, name):
            self.symbol = symbol
            self.name = name
            self.headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'Referer': 'https://finance.sina.com.cn/'
            }
        
        def get_kline(self, days=60):
            """获取K线数据"""
            url = 'https://quotes.sina.cn/cn/api/jsonp.php/var _sh{}=/CN_MarketDataService.getKLineData?symbol=sh{}&scale=240&ma=no'.format(
                self.symbol, self.symbol
            )
            try:
                r = requests.get(url, headers=self.headers, timeout=30)
                data = json.loads(re.search(r'\[.*\]', r.text).group())
                return data[-days:]
            except Exception as e:
                print(f"Error fetching data: {e}")
                return None
        
        def technical_analysis(self, klines):
            """技术面分析"""
            if not klines or len(klines) == 0:
                return None
            
            closes = [float(k['close']) for k in klines]
            volumes = [int(k['volume']) for k in klines]
            
            # 计算均线
            ma5 = statistics.mean(closes[-5:]) if len(closes) >= 5 else closes[-1]
            ma10 = statistics.mean(closes[-10:]) if len(closes) >= 10 else ma5
            ma20 = statistics.mean(closes[-20:]) if len(closes) >= 20 else ma10
            ma60 = statistics.mean(closes[-60:]) if len(closes) >= 60 else ma20
            
            current = closes[-1]
            
            # 判断趋势
            if ma5 > ma10 > ma20:
                trend = '上涨'
            elif ma5 < ma10 < ma20:
                trend = '下跌'
            else:
                trend = '震荡'
            
            # 支撑压力
            support = min(closes[-10:])
            resistance = max(closes[-10:])
            
            # 成交量分析
            avg_vol = statistics.mean(volumes[-20:]) if len(volumes) >= 20 else statistics.mean(volumes)
            vol_ratio = volumes[-1] / avg_vol if avg_vol > 0 else 1
            
            return {
                'current': current,
                'ma5': ma5,
                'ma10': ma10,
                'ma20': ma20,
                'ma60': ma60,
                'trend': trend,
                'support': support,
                'resistance': resistance,
                'vol_ratio': vol_ratio,
                'closes': closes
            }
        
        def news_analysis(self, news_list):
            """消息面分析"""
            if not news_list or len(news_list) == 0:
                return {'impact': '未知', 'reason': '未提供新闻信息', 'bullish': 0, 'bearish': 0}
            
            # 利好关键词
            bullish_keywords = ['利好', '上涨', '增长', '突破', '获批', '中标', '订单', '业绩预增', '增持', '分红', '回购', '扩产', '景气', '需求', '金价上涨', '铜价上涨']
            
            # 利空关键词
            bearish_keywords = ['利空', '下跌', '减持', '亏损', '风险', '调查', '违规', '处罚', '诉讼', '事故', '减产', '衰退', '需求下降']
            
            bullish_count = 0
            bearish_count = 0
            
            for news in news_list:
                news_lower = news.lower()
                for kw in bullish_keywords:
                    if kw in news_lower:
                        bullish_count += 1
                        break
                for kw in bearish_keywords:
                    if kw in news_lower:
                        bearish_count += 1
                        break
            
            if bullish_count > bearish_count:
                impact = '偏多'
            elif bearish_count > bullish_count:
                impact = '偏空'
            else:
                impact = '中性'
            
            return {
                'impact': impact,
                'bullish': bullish_count,
                'bearish': bearish_count,
                'reason': '利好{}条,利空{}条'.format(bullish_count, bearish_count)
            }
        
        def comprehensive_estimate(self, tech, news):
            """综合预估"""
            if not tech:
                return {'estimate': '数据获取失败', 'probability': '-', 'reason': '无法获取股票数据'}
            
            score = 0
            
            # 技术面评分
            if tech['current'] > tech['ma5']:
                score += 1
            if tech['current'] > tech['ma10']:
                score += 1
            if tech['trend'] == '上涨':
                score += 2
            elif tech['trend'] == '下跌':
                score -= 2
            
            # 消息面评分
            if news['impact'] == '偏多':
                score += 2
            elif news['impact'] == '偏空':
                score -= 2
            
            # 判定结果
            if score >= 3:
                estimate = '看涨'
                probability = '70%'
            elif score >= 1:
                estimate = '震荡偏多'
                probability = '60%'
            elif score >= -1:
                estimate = '震荡'
                probability = '50%'
            elif score >= -3:
                estimate = '震荡偏空'
                probability = '40%'
            else:
                estimate = '看跌'
                probability = '30%'
            
            # 生成理由
            reasons = []
            if tech['trend'] == '上涨':
                reasons.append('均线多头排列,短期趋势向上')
            elif tech['trend'] == '下跌':
                reasons.append('均线空头排列,短期趋势向下')
            
            if tech['current'] < tech['ma20'] * 0.9:
                reasons.append('价格处于相对低位')
            elif tech['current'] > tech['ma20'] * 1.1:
                reasons.append('价格处于相对高位')
            
            if tech['vol_ratio'] > 1.3:
                reasons.append('成交量放大')
            elif tech['vol_ratio'] < 0.7:
                reasons.append('成交量萎缩')
            
            if news.get('reason') and news['reason'] != '未提供新闻信息':
                reasons.append(news['reason'])
            
            return {
                'estimate': estimate,
                'probability': probability,
                'score': score,
                'reason': '; '.join(reasons) if reasons else '综合分析中'
            }
        
        def analyze(self, news_list=None):
            """执行完整分析"""
            print('正在获取 {} 行情数据...'.format(self.name))
            
            klines = self.get_kline(60)
            if not klines:
                return None
            
            tech = self.technical_analysis(klines)
            news = self.news_analysis(news_list or [])
            result = self.comprehensive_estimate(tech, news)
            
            return {
                'tech': tech,
                'news': news,
                'result': result
            }
    
    
    def parse_input(user_input):
        """解析用户输入,提取股票代码和新闻关键词"""
        # 匹配6位数字的股票代码
        symbol_match = re.search(r'(\d{6})', user_input)
        
        # 提取股票代码
        symbol = symbol_match.group(1) if symbol_match else None
        
        # 提取新闻关键词(排除股票代码)
        text = user_input
        if symbol_match:
            text = text.replace(symbol_match.group(), '')
        
        # 简单分词,去除常见干扰词
        stop_words = ['分析', '预估', '预测', '走势', '股票', '帮我', '看看', '这只', '怎么样', '如何', '好不好']
        words = [w.strip() for w in re.split(r'[,\s]+', text) if w.strip() and w.strip() not in stop_words]
        
        return symbol, words
    
    
    def main():
        """主函数"""
        if len(sys.argv) < 2:
            print("Usage: python stock_forecast.py <stock_code> [news_keywords...]")
            print("Example: python stock_forecast.py 601899 业绩预增 黄金价格上涨")
            sys.exit(1)
        
        symbol = sys.argv[1]
        news = sys.argv[2:] if len(sys.argv) > 2 else []
        
        # 尝试从输入推断股票名称
        name_map = {
            '601899': '紫金矿业',
            '600519': '贵州茅台',
            '000001': '平安银行',
            '600036': '招商银行',
        }
        name = name_map.get(symbol, symbol)
        
        analyzer = StockAnalyzer(symbol, name)
        result = analyzer.analyze(news)
        
        if not result:
            print("分析失败,请检查股票代码是否正确")
            sys.exit(1)
        
        tech = result['tech']
        news_result = result['news']
        estimate = result['result']
        
        print('')
        print('='*60)
        print('        {} 综合分析报告'.format(name))
        print('='*60)
        
        print('\n【技术面分析】')
        print('  当前价格: {:.2f} 元'.format(tech['current']))
        print('  MA5: {:.2f}  MA10: {:.2f}  MA20: {:.2f}'.format(tech['ma5'], tech['ma10'], tech['ma20']))
        print('  趋势判断: {}'.format(tech['trend']))
        print('  支撑位: {:.2f}  压力位: {:.2f}'.format(tech['support'], tech['resistance']))
        print('  量比: {:.2f}x'.format(tech['vol_ratio']))
        
        print('\n【消息面分析】')
        print('  影响方向: {}'.format(news_result['impact']))
        if news:
            print('  利好因素: {}条  利空因素: {}条'.format(news_result['bullish'], news_result['bearish']))
        else:
            print('  (无新闻信息,如需分析请提供相关新闻)')
        
        print('\n【综合预估】')
        print('  走势判断: {}'.format(estimate['estimate']))
        print('  预估概率: {}'.format(estimate['probability']))
        print('  分析理由: {}'.format(estimate['reason']))
        
        print('\n' + '='*60)
        print('⚠️ 此为辅助分析,仅供参考,不构成投资建议')
        print('='*60)
    
    
    if __name__ == '__main__':
        main()
  • stock_forecast_enhanced.py15 KB23bd1d4f3bd2upstream ↗
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    股价走势预估工具 - 增强版
    结合技术面 + 消息面 + 自动获取新闻
    """
    
    import json
    import os
    import re
    import statistics
    import sys
    
    try:
        import requests
    except ImportError:
        print("Error: requests module not installed")
        sys.exit(1)
    
    
    class StockNewsFetcher:
        """股票新闻获取器"""
        
        def __init__(self):
            self.headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'Referer': 'https://finance.sina.com.cn/'
            }
        
        def fetch_news(self, symbol, name):
            """尝试获取股票相关新闻"""
            news_list = []
            
            # 方法1: 尝试从新浪财经获取
            news_list.extend(self._try_sina(symbol, name))
            
            # 方法2: 尝试从东方财富获取
            news_list.extend(self._try_eastmoney(symbol, name))
            
            # 方法3: 尝试从网易财经获取
            news_list.extend(self._try_163(symbol, name))
            
            # 去重
            seen = set()
            unique_news = []
            for n in news_list:
                if n not in seen:
                    seen.add(n)
                    unique_news.append(n)
            
            return unique_news if unique_news else None
        
        def _try_sina(self, symbol, name):
            """尝试新浪财经"""
            news = []
            try:
                # 尝试新浪财经股票新闻页
                url = f'https://finance.sina.com.cn/stock/{symbol}.shtml'
                r = requests.get(url, headers=self.headers, timeout=5)
                if r.status_code == 200 and '股票' in r.text:
                    # 尝试获取新闻列表
                    keywords = ['业绩', '增长', '订单', '分红', '回购', '收购', '政策', '利好']
                    for kw in keywords:
                        if kw in r.text:
                            news.append(f'新浪财经相关报道: {kw}')
            except:
                pass
            return news
        
        def _try_eastmoney(self, symbol, name):
            """尝试东方财富"""
            news = []
            try:
                # 尝试东方财富个股新闻
                url = f'https://guba.eastmoney.com/news,{symbol}.html'
                r = requests.get(url, headers=self.headers, timeout=5)
                if r.status_code == 200:
                    keywords = ['业绩', '分红', '订单', '回购', '增持']
                    for kw in keywords:
                        if kw in r.text:
                            news.append(f'东方财富相关报道: {kw}')
            except:
                pass
            return news
        
        def _try_163(self, symbol, name):
            """尝试网易财经"""
            news = []
            try:
                url = f'https://money.163.com/stock/{symbol}.html'
                r = requests.get(url, headers=self.headers, timeout=5)
                if r.status_code == 200:
                    keywords = ['业绩', '增长', '订单', '分红']
                    for kw in keywords:
                        if kw in r.text:
                            news.append(f'网易财经相关报道: {kw}')
            except:
                pass
            return news
    
    
    class StockAnalyzer:
        """股票走势预估分析器"""
        
        def __init__(self, symbol, name, auto_fetch_news=False):
            self.symbol = symbol
            self.name = name
            self.auto_fetch_news = auto_fetch_news
            self.headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer': 'https://finance.sina.com.cn/'
            }
        
        def get_kline(self, days=60):
            """获取K线数据"""
            # 根据股票代码判断市场(沪市sh,深市sz)
            if self.symbol.startswith('6'):
                market = 'sh'
            else:
                market = 'sz'
            
            url = f'https://quotes.sina.cn/cn/api/jsonp.php/var _m{market}{self.symbol}=/CN_MarketDataService.getKLineData?symbol={market}{self.symbol}&scale=240&ma=no'
            
            try:
                r = requests.get(url, headers=self.headers, timeout=30)
                data = json.loads(re.search(r'\[.*\]', r.text).group())
                return data[-days:]
            except Exception as e:
                print(f"Error fetching data: {e}")
                return None
        
        def technical_analysis(self, klines):
            """技术面分析"""
            if not klines or len(klines) == 0:
                return None
            
            closes = [float(k['close']) for k in klines]
            volumes = [int(k['volume']) for k in klines]
            
            # 计算均线
            ma5 = statistics.mean(closes[-5:]) if len(closes) >= 5 else closes[-1]
            ma10 = statistics.mean(closes[-10:]) if len(closes) >= 10 else ma5
            ma20 = statistics.mean(closes[-20:]) if len(closes) >= 20 else ma10
            ma60 = statistics.mean(closes[-60:]) if len(closes) >= 60 else ma20
            
            current = closes[-1]
            
            # 判断趋势
            if ma5 > ma10 > ma20:
                trend = '上涨'
            elif ma5 < ma10 < ma20:
                trend = '下跌'
            else:
                trend = '震荡'
            
            # 支撑压力
            support = min(closes[-10:])
            resistance = max(closes[-10:])
            
            # 成交量分析
            avg_vol = statistics.mean(volumes[-20:]) if len(volumes) >= 20 else statistics.mean(volumes)
            vol_ratio = volumes[-1] / avg_vol if avg_vol > 0 else 1
            
            # 波动率
            returns = [(closes[i]-closes[i-1])/closes[i-1] for i in range(1, len(closes))]
            volatility = statistics.stdev(returns) if len(returns) > 1 else 0
            
            return {
                'current': current,
                'ma5': ma5,
                'ma10': ma10,
                'ma20': ma20,
                'ma60': ma60,
                'trend': trend,
                'support': support,
                'resistance': resistance,
                'vol_ratio': vol_ratio,
                'volatility': volatility,
                'closes': closes
            }
        
        def news_analysis(self, news_list):
            """消息面分析"""
            if not news_list or len(news_list) == 0:
                return {'impact': '未知', 'bullish': 0, 'bearish': 0, 'reason': '无新闻信息'}
            
            # 利好关键词
            bullish_keywords = [
                '利好', '上涨', '增长', '突破', '获批', '中标', '订单', '业绩预增', 
                '增持', '分红', '回购', '扩产', '景气', '需求', '金价', '铜价',
                '新能源', '机器人', '热管理', '空调', '制冷'
            ]
            
            # 利空关键词
            bearish_keywords = [
                '利空', '下跌', '减持', '亏损', '风险', '调查', '违规', 
                '处罚', '诉讼', '事故', '减产', '衰退', '需求下降', '竞争'
            ]
            
            bullish_count = 0
            bearish_count = 0
            news_details = []
            
            for news in news_list:
                news_lower = news.lower()
                is_bullish = False
                is_bearish = False
                
                for kw in bullish_keywords:
                    if kw in news_lower:
                        bullish_count += 1
                        is_bullish = True
                        break
                
                for kw in bearish_keywords:
                    if kw in news_lower:
                        bearish_count += 1
                        is_bearish = True
                        break
                
                if is_bullish or is_bearish:
                    news_details.append(news)
            
            if bullish_count > bearish_count:
                impact = '偏多'
            elif bearish_count > bullish_count:
                impact = '偏空'
            else:
                impact = '中性'
            
            return {
                'impact': impact,
                'bullish': bullish_count,
                'bearish': bearish_count,
                'reason': f'利好{bullish_count}条,利空{bearish_count}条',
                'details': news_details[:5] if news_details else []
            }
        
        def comprehensive_estimate(self, tech, news):
            """综合预估"""
            if not tech:
                return {'error': '无法获取股票数据'}
            
            score = 0
            
            # 技术面评分
            if tech['current'] > tech['ma5']:
                score += 1
            if tech['current'] > tech['ma10']:
                score += 1
            if tech['trend'] == '上涨':
                score += 2
            elif tech['trend'] == '下跌':
                score -= 2
            
            # 消息面评分
            if news['impact'] == '偏多':
                score += 2
            elif news['impact'] == '偏空':
                score -= 2
            
            # 生成预估
            if score >= 3:
                est_next = '上涨'
                prob_next = '70%'
            elif score >= 1:
                est_next = '震荡偏多'
                prob_next = '60%'
            elif score >= -1:
                est_next = '震荡'
                prob_next = '50%'
            elif score >= -3:
                est_next = '震荡偏空'
                prob_next = '40%'
            else:
                est_next = '下跌'
                prob_next = '30%'
            
            # 生成各周期预估
            return self._generate_multi_period_estimate(tech, news, score, prob_next)
        
        def _generate_multi_period_estimate(self, tech, news, score, prob_next='50%'):
            """生成多周期预估"""
            current = tech['current']
            closes = tech['closes']
            
            # 消息面影响系数(随时间递减)
            news_score = news['bullish'] - news['bearish']
            news_effect_next = news_score * 0.02
            news_effect_week = news_score * 0.015
            news_effect_month = news_score * 0.01
            
            # 技术面趋势
            ma10_trend = (tech['ma10'] - closes[-5]) / closes[-5]
            ma20_trend = (tech['ma20'] - closes[-20]) / closes[-20]
            
            # 次日预估
            next_tech = 0.02 if tech['trend'] == '上涨' else (-0.02 if tech['trend'] == '下跌' else 0)
            next_total = next_tech + news_effect_next
            next_price_low = current * 0.98
            next_price_high = current * 1.02
            next_dir = '上涨' if next_total > 0.01 else ('下跌' if next_total < -0.01 else '震荡')
            
            # 7日预估
            week_total = ma10_trend + news_effect_week
            week_price = current * (1 + week_total)
            week_dir = '上涨' if week_total > 0.02 else ('下跌' if week_total < -0.02 else '震荡')
            
            # 30日预估
            month_total = ma20_trend + news_effect_month
            month_price = current * (1 + month_total)
            month_dir = '上涨' if month_total > 0.03 else ('下跌' if month_total < -0.03 else '震荡')
            
            return {
                'next': {
                    'price_range': f'{next_price_low:.2f}~{next_price_high:.2f}',
                    'direction': next_dir,
                    'probability': prob_next
                },
                'week': {
                    'price': f'{week_price:.2f}',
                    'direction': week_dir
                },
                'month': {
                    'price': f'{month_price:.2f}',
                    'direction': month_dir
                },
                'news_score': news_score
            }
        
        def analyze(self, news_from_user=None):
            """执行完整分析"""
            print(f'正在获取 {self.name} 行情数据...')
            
            klines = self.get_kline(60)
            if not klines:
                return {'error': '无法获取行情数据'}
            
            # 获取技术面
            tech = self.technical_analysis(klines)
            
            # 获取消息面
            news_list = []
            news_source = ''
            
            if news_from_user and len(news_from_user) > 0:
                news_list = news_from_user
                news_source = '用户提供'
            elif self.auto_fetch_news:
                print(f'正在尝试自动获取 {self.name} 相关新闻...')
                fetcher = StockNewsFetcher()
                fetched = fetcher.fetch_news(self.symbol, self.name)
                if fetched:
                    news_list = fetched
                    news_source = '自动获取'
            
            news = self.news_analysis(news_list)
            if news_source:
                news['source'] = news_source
            
            # 综合预估
            result = self.comprehensive_estimate(tech, news)
            
            return {
                'tech': tech,
                'news': news,
                'result': result
            }
    
    
    def main():
        """主函数"""
        if len(sys.argv) < 2:
            print("用法: python stock_forecast_enhanced.py <股票代码> [自动获取新闻] [用户新闻...]")
            print("示例: python stock_forecast_enhanced.py 601899 true 业绩预增 金价上涨")
            sys.exit(1)
        
        symbol = sys.argv[1]
        auto_fetch = len(sys.argv) > 2 and sys.argv[2].lower() == 'true'
        user_news = sys.argv[3:] if len(sys.argv) > 3 else []
        
        # 股票名称映射
        name_map = {
            '601899': '紫金矿业',
            '600519': '贵州茅台',
            '000001': '平安银行',
            '600036': '招商银行',
            '002050': '三花智控',
        }
        name = name_map.get(symbol, symbol)
        
        analyzer = StockAnalyzer(symbol, name, auto_fetch_news=auto_fetch)
        result = analyzer.analyze(user_news)
        
        if 'error' in result:
            print(f"错误: {result['error']}")
            sys.exit(1)
        
        tech = result['tech']
        news = result['news']
        est = result['result']
        
        print('')
        print('='*65)
        print(f'       {name}({symbol}) 综合分析报告')
        print('='*65)
        
        print('\n【基础信息】')
        print(f'  当前价格: {tech["current"]:.2f} 元')
        print(f'  日波动率: {tech["volatility"]*100:.2f}%')
        
        print('\n【技术面】')
        print(f'  MA5: {tech["ma5"]:.2f}  MA10: {tech["ma10"]:.2f}  MA20: {tech["ma20"]:.2f}')
        print(f'  趋势: {tech["trend"]}')
        print(f'  支撑: {tech["support"]:.2f}  压力: {tech["resistance"]:.2f}')
        print(f'  量比: {tech["vol_ratio"]:.2f}x')
        
        print('\n【消息面】')
        if news.get('source'):
            print(f'  来源: {news["source"]}')
        print(f'  方向: {news["impact"]}')
        if news['bullish'] > 0 or news['bearish'] > 0:
            print(f'  利好: {news["bullish"]}条  利空: {news["bearish"]}条')
        else:
            print(f'  ({news["reason"]})')
        
        print('')
        print('='*65)
        print('                    多周期预估结果')
        print('='*65)
        
        print(f'\n📅 次日')
        print(f'  预估区间: {est["next"]["price_range"]} 元')
        print(f'  方向: {est["next"]["direction"]}  概率: {est["next"]["probability"]}')
        
        print(f'\n📆 7日后')
        print(f'  预估价格: {est["week"]["price"]} 元')
        print(f'  方向: {est["week"]["direction"]}')
        
        print(f'\n📆 30日后')
        print(f'  预估价格: {est["month"]["price"]} 元')
        print(f'  方向: {est["month"]["direction"]}')
        
        print('')
        print('='*65)
        print('⚠️ 消息面影响随时间递减,技术面主导中长期趋势')
        print('⚠️ 此为辅助分析,仅供参考,不构成投资建议')
        print('='*65)
    
    
    if __name__ == '__main__':
        main()
  • stock_learn.py7.6 KB8626488679a4upstream ↗
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    股价走势预估工具 - 智能学习版
    具备自主了解股票概念的能力
    """
    
    import json
    import re
    import statistics
    import sys
    import os
    
    try:
        import requests
    except ImportError:
        sys.exit(1)
    
    
    # 股票概念知识库(自动扩展)
    STOCK_KNOWLEDGE = {
        '002050': {
            'name': '三花智控',
            'industry': '新能源车热管理',
            'concepts': ['特斯拉概念', '机器人概念', '人形机器人', 'Optimus', '微通道换热器'],
            'keywords': ['新能源车', '热管理', '制冷', '空调', '特斯拉', '机器人', '订单', '业绩', '比亚迪']
        },
        '601899': {
            'name': '紫金矿业',
            'industry': '黄金开采',
            'concepts': ['黄金概念', '避险资产', '有色金属', '铜'],
            'keywords': ['黄金', '金价', '有色金属', '铜', '矿产', '中东', '避险', '央行', '业绩']
        },
    }
    
    # 知识库文件路径
    KNOWLEDGE_FILE = '/home/admin/.openclaw/workspace/memory/stock_knowledge.json'
    
    
    class StockKnowledgeLearner:
        """股票概念学习器"""
        
        def __init__(self):
            self.knowledge = STOCK_KNOWLEDGE.copy()
            self._load_knowledge()
        
        def _load_knowledge(self):
            """加载本地知识库"""
            if os.path.exists(KNOWLEDGE_FILE):
                try:
                    with open(KNOWLEDGE_FILE, 'r') as f:
                        saved = json.load(f)
                        self.knowledge.update(saved)
                except:
                    pass
        
        def _save_knowledge(self):
            """保存知识库"""
            with open(KNOWLEDGE_FILE, 'w') as f:
                json.dump(self.knowledge, f, ensure_ascii=False, indent=2)
        
        def learn(self, symbol, name, concepts_or_keywords):
            """学习新的股票概念"""
            if symbol not in self.knowledge:
                self.knowledge[symbol] = {
                    'name': name,
                    'industry': '未知',
                    'concepts': [],
                    'keywords': []
                }
            
            # 更新概念和关键词
            for item in concepts_or_keywords:
                if item not in self.knowledge[symbol]['concepts']:
                    self.knowledge[symbol]['concepts'].append(item)
                if item not in self.knowledge[symbol]['keywords']:
                    self.knowledge[symbol]['keywords'].append(item)
            
            self._save_knowledge()
            print(f"✅ 已学习: {name}({symbol}) - 新增概念: {concepts_or_keywords}")
        
        def get_knowledge(self, symbol, name=None):
            """获取股票知识"""
            if symbol in self.knowledge:
                return self.knowledge[symbol]
            
            # 如果没有,返回默认结构
            return {
                'name': name or symbol,
                'industry': '未知',
                'concepts': [],
                'keywords': [name] if name else []
            }
        
        def get_all_concepts(self, symbol):
            """获取某股票所有概念"""
            info = self.get_knowledge(symbol)
            return info.get('concepts', []) + info.get('keywords', [])
    
    
    class StockAnalyzer:
        """股票分析器"""
        
        def __init__(self, symbol, name=None, learner=None):
            self.symbol = symbol
            self.learner = learner or StockKnowledgeLearner()
            self.info = self.learner.get_knowledge(symbol, name)
            self.name = self.info['name']
            
            self.headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer': 'https://finance.sina.com.cn/'
            }
        
        def get_kline(self, days=60):
            market = 'sh' if self.symbol.startswith('6') else 'sz'
            url = f'https://quotes.sina.cn/cn/api/jsonp.php/var _m{market}{self.symbol}=/CN_MarketDataService.getKLineData?symbol={market}{self.symbol}&scale=240&ma=no'
            
            try:
                r = requests.get(url, headers=self.headers, timeout=30)
                data = json.loads(re.search(r'\[.*\]', r.text).group())
                return data[-days:]
            except:
                return None
        
        def analyze(self, user_news=None):
            print(f'正在分析 {self.name}...')
            
            # 获取概念关键词
            concepts = self.learner.get_all_concepts(self.symbol)
            print(f'  已掌握概念: {concepts}')
            
            klines = self.get_kline(60)
            if not klines:
                return {'error': '无法获取数据'}
            
            # 技术分析
            closes = [float(k['close']) for k in klines]
            volumes = [int(k['volume']) for k in klines]
            
            ma5 = statistics.mean(closes[-5:])
            ma10 = statistics.mean(closes[-10:])
            ma20 = statistics.mean(closes[-20:])
            current = closes[-1]
            
            trend = '上涨' if ma5 > ma10 > ma20 else ('下跌' if ma5 < ma10 < ma20 else '震荡')
            
            # 消息分析
            news_keywords = concepts + (user_news or [])
            bullish = sum([1 for kw in news_keywords if any(k in kw for k in ['增长','订单','业绩','特斯拉','机器人','利好','突破'])])
            bearish = sum([1 for kw in news_keywords if any(k in kw for k in ['下跌','利空','减持','亏损','风险'])])
            
            impact = '偏多' if bullish > bearish else ('偏空' if bearish > bullish else '中性')
            news_score = bullish - bearish
            
            # 预估
            score = 0
            if current > ma5: score += 1
            if current > ma10: score += 1
            if trend == '上涨': score += 2
            elif trend == '下跌': score -= 2
            score += news_score
            
            next_dir = '上涨' if score >= 2 else ('下跌' if score <= -2 else '震荡')
            week_dir = '上涨' if (ma10-closes[-5])/closes[-5] + news_score*0.015 > 0.02 else ('下跌' if (ma10-closes[-5])/closes[-5] + news_score*0.015 < -0.02 else '震荡')
            month_dir = '上涨' if (ma20-closes[-20])/closes[-20] + news_score*0.01 > 0.03 else ('下跌' if (ma20-closes[-20])/closes[-20] + news_score*0.01 < -0.03 else '震荡')
            
            return {
                'name': self.name,
                'symbol': self.symbol,
                'concepts': concepts,
                'current': current,
                'trend': trend,
                'ma5': ma5, 'ma10': ma10, 'ma20': ma20,
                'impact': impact,
                'bullish': bullish,
                'next': {'range': f'{current*0.98:.2f}~{current*1.02:.2f}', 'dir': next_dir},
                'week': {'price': f'{current*(1+(ma10-closes[-5])/closes[-5]+news_score*0.015):.2f}', 'dir': week_dir},
                'month': {'price': f'{current*(1+(ma20-closes[-20])/closes[-20]+news_score*0.01):.2f}', 'dir': month_dir}
            }
    
    
    def main():
        if len(sys.argv) < 2:
            print("用法: python stock_learn.py <股票代码> [用户消息...]")
            print("示例: python stock_learn.py 002050 业绩预增 特斯拉机器人订单")
            sys.exit(1)
        
        symbol = sys.argv[1]
        user_news = sys.argv[2:] if len(sys.argv) > 2 else []
        
        analyzer = StockAnalyzer(symbol)
        result = analyzer.analyze(user_news)
        
        if 'error' in result:
            print(f"错误: {result['error']}")
            sys.exit(1)
        
        print('')
        print('='*55)
        print(f'  {result["name"]}({result["symbol"]}) 综合分析')
        print('='*55)
        print(f'已掌握概念: {result["concepts"]}')
        print(f'当前价格: {result["current"]:.2f}元 | 趋势: {result["trend"]}')
        print(f'消息面: {result["impact"]} (利好{result["bullish"]}条)')
        print('')
        print(f'📅 次日: {result["next"]["range"]} -> {result["next"]["dir"]}')
        print(f'📆 7日:  {result["week"]["price"]}元 -> {result["week"]["dir"]}')
        print(f'📆 30日: {result["month"]["price"]}元 -> {result["month"]["dir"]}')
        print('='*55)
    
    
    if __name__ == '__main__':
        main()
  • stock_smart.py11 KB8a689eb50aa9upstream ↗
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    股价走势预估工具 - 智能新闻检索版
    结合技术面 + 行业面 + 消息面 综合分析
    """
    
    import json
    import os
    import re
    import statistics
    import sys
    
    try:
        import requests
    except ImportError:
        print("Error: requests module not installed")
        sys.exit(1)
    
    
    # 股票行业关键词映射
    STOCK_KEYWORDS = {
        '002050': {  # 三花智控
            'name': '三花智控',
            'industry': '新能源车热管理',
            'keywords': ['新能源车', '热管理', '制冷', '空调', '零部件', '比亚迪', '特斯拉', '订单', '业绩'],
            'sector': '新能源车产业链'
        },
        '601899': {  # 紫金矿业
            'name': '紫金矿业',
            'industry': '黄金开采',
            'keywords': ['黄金', '金价', '有色金属', '铜', '矿产', '中东', '避险', '央行'],
            'sector': '贵金属'
        },
        '600519': {  # 贵州茅台
            'name': '贵州茅台',
            'industry': '白酒',
            'keywords': ['白酒', '茅台', '消费', '酒', '高端消费', '业绩', '分红'],
            'sector': '消费'
        },
    }
    
    
    class SmartNewsFetcher:
        """智能新闻获取器 - 基于行业关键词检索"""
        
        def __init__(self):
            self.headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'Referer': 'https://finance.sina.com.cn/'
            }
        
        def fetch_news(self, symbol, name=None, industry_keywords=None):
            """智能获取相关新闻"""
            
            # 获取股票的行业关键词
            stock_info = STOCK_KEYWORDS.get(symbol, {})
            keywords = industry_keywords or stock_info.get('keywords', [name])
            
            print(f'  检索关键词: {keywords}')
            
            news_list = []
            
            # 方法1: 基于行业关键词搜索
            for kw in keywords[:5]:  # 限制搜索次数
                results = self._search_by_keyword(kw)
                news_list.extend(results)
            
            # 去重
            seen = set()
            unique_news = []
            for n in news_list:
                if n['keyword'] not in seen:
                    seen.add(n['keyword'])
                    unique_news.append(n)
            
            if unique_news:
                print(f'  找到 {len(unique_news)} 条相关资讯')
                return unique_news
            
            return None
        
        def _search_by_keyword(self, keyword):
            """根据关键词搜索新闻"""
            results = []
            
            # 尝试不同的搜索端点
            search_urls = [
                # 新浪搜索
                f'https://searchapi.sina.com.cn/sina/search.php?q={keyword}&c=news&sort=time',
            ]
            
            for url in search_urls:
                try:
                    r = requests.get(url, headers=self.headers, timeout=5)
                    if r.status_code == 200:
                        # 提取关键词匹配的内容
                        if keyword in r.text:
                            results.append({
                                'keyword': keyword,
                                'source': 'sina',
                                'content': f'{keyword}相关行业资讯'
                            })
                except:
                    continue
            
            return results
    
    
    class StockAnalyzer:
        """股票走势预估分析器"""
        
        def __init__(self, symbol, name=None, auto_fetch_news=True):
            self.symbol = symbol
            self.name = name or STOCK_KEYWORDS.get(symbol, {}).get('name', symbol)
            self.auto_fetch_news = auto_fetch_news
            
            self.headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer': 'https://finance.sina.com.cn/'
            }
        
        def get_kline(self, days=60):
            """获取K线数据"""
            # 根据股票代码判断市场
            if self.symbol.startswith('6'):
                market = 'sh'
            else:
                market = 'sz'
            
            url = f'https://quotes.sina.cn/cn/api/jsonp.php/var _m{market}{self.symbol}=/CN_MarketDataService.getKLineData?symbol={market}{self.symbol}&scale=240&ma=no'
            
            try:
                r = requests.get(url, headers=self.headers, timeout=30)
                data = json.loads(re.search(r'\[.*\]', r.text).group())
                return data[-days:]
            except Exception as e:
                print(f"Error fetching data: {e}")
                return None
        
        def technical_analysis(self, klines):
            """技术面分析"""
            if not klines:
                return None
            
            closes = [float(k['close']) for k in klines]
            volumes = [int(k['volume']) for k in klines]
            
            ma5 = statistics.mean(closes[-5:])
            ma10 = statistics.mean(closes[-10:])
            ma20 = statistics.mean(closes[-20:])
            ma60 = statistics.mean(closes[-60:]) if len(closes) >= 60 else ma20
            current = closes[-1]
            
            if ma5 > ma10 > ma20:
                trend = '上涨'
            elif ma5 < ma10 < ma20:
                trend = '下跌'
            else:
                trend = '震荡'
            
            support = min(closes[-10:])
            resistance = max(closes[-10:])
            avg_vol = statistics.mean(volumes[-20:])
            vol_ratio = volumes[-1] / avg_vol
            
            returns = [(closes[i]-closes[i-1])/closes[i-1] for i in range(1, len(closes))]
            volatility = statistics.stdev(returns) if len(returns) > 1 else 0
            
            return {
                'current': current,
                'ma5': ma5, 'ma10': ma10, 'ma20': ma20, 'ma60': ma60,
                'trend': trend,
                'support': support, 'resistance': resistance,
                'vol_ratio': vol_ratio, 'volatility': volatility,
                'closes': closes
            }
        
        def news_analysis(self, news_list):
            """消息面分析"""
            if not news_list:
                return {'impact': '未知', 'bullish': 0, 'bearish': 0, 'reason': '无行业资讯'}
            
            # 行业相关关键词
            bullish_keywords = ['利好', '上涨', '增长', '突破', '获批', '中标', '订单', '业绩预增', 
                              '增持', '分红', '回购', '扩产', '景气', '需求', '金价', '新能源', '热管理']
            bearish_keywords = ['利空', '下跌', '减持', '亏损', '风险', '调查', '违规', '减产', '衰退']
            
            bullish = bearish = 0
            keywords_found = []
            
            for news in news_list:
                kw = news.get('keyword', '').lower()
                for bk in bullish_keywords:
                    if bk in kw:
                        bullish += 1
                        keywords_found.append(bk)
                        break
                for bk in bearish_keywords:
                    if bk in kw:
                        bearish += 1
                        keywords_found.append(bk)
                        break
            
            impact = '偏多' if bullish > bearish else ('偏空' if bearish > bullish else '中性')
            
            return {
                'impact': impact,
                'bullish': bullish,
                'bearish': bearish,
                'reason': f'行业相关: {", ".join(set(keywords_found[:3]))}' if keywords_found else '行业资讯中性',
                'details': [n['keyword'] for n in news_list[:3]]
            }
        
        def estimate(self, tech, news):
            """综合预估"""
            score = 0
            
            if tech['current'] > tech['ma5']: score += 1
            if tech['current'] > tech['ma10']: score += 1
            if tech['trend'] == '上涨': score += 2
            elif tech['trend'] == '下跌': score -= 2
            
            if news['impact'] == '偏多': score += 2
            elif news['impact'] == '偏空': score -= 2
            
            # 多周期预估
            current = tech['current']
            news_score = news['bullish'] - news['bearish']
            
            next_dir = '上涨' if score >= 1 else ('下跌' if score <= -3 else '震荡')
            week_tech = (tech['ma10'] - tech['closes'][-5]) / tech['closes'][-5]
            week_dir = '上涨' if week_tech + news_score*0.015 > 0.02 else ('下跌' if week_tech + news_score*0.015 < -0.02 else '震荡')
            month_tech = (tech['ma20'] - tech['closes'][-20]) / tech['closes'][-20]
            month_dir = '上涨' if month_tech + news_score*0.01 > 0.03 else ('下跌' if month_tech + news_score*0.01 < -0.03 else '震荡')
            
            return {
                'next': {'range': f'{current*0.98:.2f}~{current*1.02:.2f}', 'direction': next_dir},
                'week': {'price': f'{current*(1+week_tech+news_score*0.015):.2f}', 'direction': week_dir},
                'month': {'price': f'{current*(1+month_tech+news_score*0.01):.2f}', 'direction': month_dir}
            }
        
        def analyze(self, user_news=None):
            """执行分析"""
            print(f'正在获取 {self.name} 行情数据...')
            
            klines = self.get_kline(60)
            if not klines:
                return {'error': '无法获取行情数据'}
            
            tech = self.technical_analysis(klines)
            
            # 获取行业资讯
            news_list = None
            if self.auto_fetch_news:
                print(f'正在检索 {self.name} 相关行业资讯...')
                fetcher = SmartNewsFetcher()
                news_list = fetcher.fetch_news(self.symbol, self.name)
            
            news = self.news_analysis(news_list or user_news or [])
            result = self.estimate(tech, news)
            
            return {'tech': tech, 'news': news, 'result': result, 'source': '智能检索' if news_list else '用户提供'}
    
    
    def main():
        if len(sys.argv) < 2:
            print("用法: python stock_smart.py <股票代码> [用户消息...]")
            sys.exit(1)
        
        symbol = sys.argv[1]
        user_news = sys.argv[2:] if len(sys.argv) > 2 else []
        
        analyzer = StockAnalyzer(symbol, auto_fetch_news=True)
        result = analyzer.analyze(user_news)
        
        if 'error' in result:
            print(f"错误: {result['error']}")
            sys.exit(1)
        
        tech = result['tech']
        news = result['news']
        est = result['result']
        
        print('')
        print('='*60)
        print(f'       {result.get("source", "")} - {tech["ma10"]:.2f}({symbol}) 综合分析')
        print('='*60)
        
        print(f'\n当前价格: {tech["current"]:.2f} 元 | 趋势: {tech["trend"]}')
        print(f'MA5:{tech["ma5"]:.2f} MA10:{tech["ma10"]:.2f} MA20:{tech["ma20"]:.2f}')
        print(f'支撑:{tech["support"]:.2f} 压力:{tech["resistance"]:.2f}')
        
        print(f'\n消息面: {news["impact"]} ({news["reason"]})')
        
        print('')
        print('='*60)
        print('多周期预估:')
        print(f'  📅 次日: {est["next"]["range"]}元 -> {est["next"]["direction"]}')
        print(f'  📆 7日:  {est["week"]["price"]}元 -> {est["week"]["direction"]}')
        print(f'  📆 30日: {est["month"]["price"]}元 -> {est["month"]["direction"]}')
        print('='*60)
        print('⚠️ 仅供参考,不构成投资建议')
    
    
    if __name__ == '__main__':
        main()

Plain-text copy, no login: /skill-bundles/qiangqiang233-stock-forecast.md

// REPO STATS

0 stars
0 open issues
Last commit: 8mo ago