# TANZG 量价分析引擎 - 分析引擎 (V2.1.0 增强版) import os import akshare as ak import pandas as pd import json import re import threading import queue import subprocess from datetime import datetime, timedelta from functools import lru_cache # 股票名称到代码映射(通过搜索获取) STOCK_NAME_CACHE = {} def _search_sina_with_timeout(name: str, timeout_sec: float = 5.0): """通过 Sina 搜索接口查询股票代码(带超时保护)""" import requests as _req result_queue = queue.Queue() def _worker(): try: # Sina 股票搜索接口 url = f'https://suggest3.sinajs.cn/suggest/type=11,12,13,14,15,18&key={name}' headers = { 'Referer': 'https://finance.sina.com.cn', 'User-Agent': 'Mozilla/5.0', } r = _req.get(url, headers=headers, timeout=timeout_sec) r.encoding = 'utf-8' # 返回格式: var suggest_result ="name|code|name|name..."; text = r.text # 提取引号内的内容 m = re.search(r'"([^"]+)"', text) if m: result_queue.put(('ok', m.group(1))) else: result_queue.put(('ok', '')) except Exception as e: result_queue.put(('err', str(e))) t = threading.Thread(target=_worker, daemon=True) t.start() t.join(timeout=timeout_sec) if t.is_alive(): return None # 超时 if result_queue.empty(): return None status, val = result_queue.get_nowait() return val if status == 'ok' else None def _search_akshare_with_timeout(name: str, timeout_sec: float = 4.0): """在子线程中执行 akshare 查询,超时则抛异常 修复:增加更严格的超时控制和错误处理 """ result_queue = queue.Queue() def _worker(): try: # 设置socket超时,防止akshare长时间阻塞 import socket old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout_sec) df = ak.stock_zh_a_spot_em() result_queue.put(('ok', df)) except Exception as e: result_queue.put(('err', str(e))) finally: try: socket.setdefaulttimeout(old_timeout) except: pass t = threading.Thread(target=_worker, daemon=True) t.start() t.join(timeout=timeout_sec) if t.is_alive(): # 线程仍然存活,说明超时 return None # 超时 if result_queue.empty(): return None status, val = result_queue.get_nowait() return val if status == 'ok' else None def search_stock_by_name(name: str): """通过名称搜索股票代码(带超时保护)""" if name in STOCK_NAME_CACHE: return STOCK_NAME_CACHE[name] # 优先尝试 Sina 搜索(快速) sina_result = _search_sina_with_timeout(name, timeout_sec=5.0) if sina_result: # Sina返回格式: "name,type,code,shcode,name,...;name2,type2,code2,..." # 分割每个条目(用分号或直接按逗号解析) parts = sina_result.split(';') for part in parts: if not part.strip(): continue segs = part.split(',') if len(segs) >= 3: found_name = segs[0].strip() code = segs[2].strip() # 第3个字段是6位代码 if not code or len(code) != 6: continue # 精确匹配优先 if found_name == name: market = 'SZ' if code.startswith(('000', '002', '003', '300')) else 'SH' ts_code = f"{code}.{market}" STOCK_NAME_CACHE[name] = ts_code return ts_code # 取第一个结果作为模糊匹配 for part in parts: if not part.strip(): continue segs = part.split(',') if len(segs) >= 3: code = segs[2].strip() if code and len(code) == 6: market = 'SZ' if code.startswith(('000', '002', '003', '300')) else 'SH' ts_code = f"{code}.{market}" STOCK_NAME_CACHE[name] = ts_code return ts_code # 备用:akshare 精确/模糊匹配 df = _search_akshare_with_timeout(name, timeout_sec=6.0) if df is not None: # 精确匹配名称 exact = df[df['名称'] == name] if not exact.empty: code = exact.iloc[0]['代码'] market = 'SZ' if code.startswith(('000', '002', '003', '300')) else 'SH' ts_code = f"{code}.{market}" STOCK_NAME_CACHE[name] = ts_code return ts_code # 模糊匹配 fuzzy = df[df['名称'].str.contains(name, na=False)] if not fuzzy.empty: code = fuzzy.iloc[0]['代码'] name_found = fuzzy.iloc[0]['名称'] market = 'SZ' if code.startswith(('000', '002', '003', '300')) else 'SH' ts_code = f"{code}.{market}" STOCK_NAME_CACHE[name] = ts_code return ts_code # 硬编码常见股票(最终备用) known = { '深南电路': '002916.SZ', '壹网壹创': '300792.SZ', '天桥起重': '002523.SZ', '蜂助手': '301382.SZ', '宏昌科技': '301008.SZ', '贵州茅台': '600519.SH', '宁德时代': '300750.SZ', '比亚迪': '002594.SZ', '东方财富': '300059.SZ', '中信证券': '600030.SH', '中红医疗': '300981.SZ', } if name in known: STOCK_NAME_CACHE[name] = known[name] return known[name] return None def parse_ts_code(ts_code: str) -> tuple: """解析股票代码,返回(symbol, market)""" ts_code = ts_code.strip().upper() # 如果已是带后缀的格式 if '.' in ts_code: code, market = ts_code.split('.') market = market.lower() # 统一小写(Sina/东方财富格式) else: code = ts_code # 判断市场 if code.startswith(('000', '002', '003', '300')): market = 'sz' elif code.startswith(('600', '601', '603', '688')): market = 'sh' else: market = 'sz' # 默认深圳 return code.lower(), market def _to_wstock_code(ts_code: str) -> str: """将 ts_code (如 600519.SH) 转换为 westock-data 格式 (如 sh600519)""" code = ts_code.split('.')[0] code = code.lower() if code.startswith(('6', '9')): return f"sh{code}" else: return f"sz{code}" def get_stock_quote(ts_code: str): """获取单只股票实时/当日行情(优先Sina实时,不可用则用K线最新数据)""" import requests code, market = parse_ts_code(ts_code) sym = f'{market}{code}' try: headers = {'Referer': 'https://finance.sina.com.cn', 'User-Agent': 'Mozilla/5.0'} url = f'https://hq.sinajs.cn/list={sym}' r = requests.get(url, headers=headers, timeout=10) r.encoding = 'gb18030' m = re.search(r'hq_str_\w+="([^"]+)"', r.text) if m and m.group(1) and len(m.group(1)) > 10: fields = m.group(1).split(',') # fields[0] 是股票名称 stock_name = fields[0].strip() if fields and len(fields) > 0 else ts_code # Sina数据格式固定:name,open,prev_close,price,high,low,buy1,sell1,vol,amount,... # 直接使用固定索引,不依赖len()-N # 增加字段数量校验,防止API返回格式变化导致解析错误 if len(fields) < 10: raise ValueError(f'Sina API返回字段不足,期望至少10个字段,实际只有{len(fields)}个') price = float(fields[1]) prev_close = float(fields[2]) open_p = float(fields[3]) high = float(fields[4]) low = float(fields[5]) vol = float(fields[8]) # 成交量在索引8 amount = float(fields[9]) # 成交额在索引9 pct = (price - prev_close) / prev_close * 100 if prev_close else 0 return { 'ts_code': ts_code, 'name': stock_name, 'price': price, 'open': open_p, 'high': high, 'low': low, 'prev_close': prev_close, 'change': round(price - prev_close, 2), 'pct_change': round(pct, 2), 'volume': int(vol), 'amount': amount, 'time': '', } except Exception: pass # 备用:从K线数据获取最新当日数据(稳定可靠) try: df = get_stock_kline(ts_code, days=3) if df is not None and not df.empty: latest = df.iloc[-1] prev = df.iloc[-2] if len(df) > 1 else latest pct = ((latest['close'] - prev['close']) / prev['close'] * 100) if prev['close'] > 0 else 0 # 尝试获取股票名称(可能从K线数据的某列) stock_name = ts_code if 'name' in latest and latest['name']: stock_name = latest['name'] return { 'ts_code': ts_code, 'name': stock_name, 'price': latest['close'], 'open': latest['open'], 'high': latest['high'], 'low': latest['low'], 'prev_close': prev['close'], 'change': round(latest['close'] - prev['close'], 2), 'pct_change': round(pct, 2), 'volume': int(latest['volume']), 'amount': 0, 'time': latest.get('date', ''), } except Exception: pass return None def get_stock_kline(ts_code: str, days=30): """获取股票K线数据(直接HTTP调用Sina,稳定绕过akshare的JS解码问题)""" import time, requests code, market = parse_ts_code(ts_code) symbol = f'{market}{code}' headers = {'Referer': 'https://finance.sina.com.cn', 'User-Agent': 'Mozilla/5.0'} url = (f'https://quotes.sina.cn/cn/api/jsonp_v2.php/=/CN_MarketDataService.getKLineData' f'?symbol={symbol}&scale=240&datalen={days + 100}&ma=no') for attempt in range(3): try: r = requests.get(url, headers=headers, timeout=15) r.encoding = 'utf-8' raw = r.text.strip() # Sina返回格式: /**/=([{...}]) # 先去掉script标签 clean = re.sub(r'/\*.*?\*/', '', raw, flags=re.DOTALL).strip() # 解析 =(...) m = re.search(r'=\s*\((.+)\)\s*;?\s*$', clean, re.DOTALL) if not m: raise ValueError(f"Sina返回格式异常: {raw[:200]}") data = json.loads(m.group(1)) if not data: raise ValueError("Sina返回空数据") rows = [] for item in data: rows.append({ 'date': item.get('day', ''), 'open': float(item.get('open', 0)), 'high': float(item.get('high', 0)), 'low': float(item.get('low', 0)), 'close': float(item.get('close', 0)), 'volume': float(item.get('volume', 0)), }) df = pd.DataFrame(rows) df = df.tail(days).copy() df['vol_w'] = (df['volume'] / 10000).round(2) df['pct'] = ((df['close'] - df['close'].shift(1)) / df['close'].shift(1) * 100).round(2) df['amount_bn'] = 0.0 return df.reset_index(drop=True) except ValueError: raise except Exception as e: if attempt < 2: time.sleep(2) continue raise ValueError(f"无法获取 {ts_code} 的K线数据: {e}") def get_augmented_kline(ts_code: str, days=65): """ 获取K线数据及增强字段(turnover + amount) 数据获取链路: K线主体: 新浪 (现有 get_stock_kline 逻辑) turnover/amount: westock-data → 新浪(跳过) → 东方财富 → AKShare 返回DataFrame,增加: - amount: 成交额(元) - turnover: 换手率(%) """ # Step 1: 从Sina获取基础K线 (现有逻辑,不变) df = get_stock_kline(ts_code, days) # Step 2: 增量获取 turnover + amount(按优先级链) supplement = {} # ── 第1优先: westock-data ── try: wc = _to_wstock_code(ts_code) result = subprocess.run( ['westock-data', 'kline', wc, '--period', 'day', '--limit', str(days)], capture_output=True, text=True, timeout=news_timeout ) if result.returncode == 0 and result.stdout.strip(): data = json.loads(result.stdout) klines = data.get('data', data.get('kline', data if isinstance(data, list) else [])) if isinstance(klines, list): for item in klines: date_str = str(item.get('date', item.get('day', '')))[:10] if date_str: supplement[date_str] = { 'amount': float(item.get('amount', item.get('amo', 0)) or 0), 'turnover': float(item.get('turnover', item.get('turn', 0)) or 0), } except Exception: pass # ── 第2优先: 新浪(跳过 - K线JSONP不含amount/turnover) ── # ── 第3优先: 东方财富 ── if not supplement: try: import requests as _req code, market = parse_ts_code(ts_code) secid = f"0.{code}" if market in ('sz', 'shenzhen') else f"1.{code}" url = (f"https://push2his.eastmoney.com/api/qt/stock/kline/get" f"?secid={secid}&fields=f43,f44,f45,f46,f47,f48,f168" f"&klt=101&fqt=1&end=20500101&lmt={days + 100}") headers = {'User-Agent': 'Mozilla/5.0', 'Referer': 'https://quote.eastmoney.com/'} resp = _req.get(url, headers=headers, timeout=8) data = resp.json() if data and 'data' in data and 'klines' in data['data']: for line in data['data']['klines']: parts = line.split(',') if len(parts) >= 8: date_str = parts[0].split(' ')[0] supplement[date_str] = { 'amount': float(parts[6]) if parts[6] else 0, 'turnover': float(parts[7]) if parts[7] else 0, } except Exception: pass # ── 第4优先: AKShare ── if not supplement: try: code = ts_code.split('.')[0] hist = ak.stock_zh_a_hist( symbol=code, adjust="qfq", start_date=(datetime.now() - timedelta(days=days)).strftime('%Y%m%d'), end_date=datetime.now().strftime('%Y%m%d') ) if hist is not None and not hist.empty: for _, row in hist.iterrows(): date_str = str(row['日期']) supplement[date_str] = { 'amount': float(row.get('成交额', 0) or 0), 'turnover': float(row.get('换手率', 0) or 0), } except Exception: pass # Step 3: 将补充字段merge到DataFrame if supplement: df['date_str'] = df['date'].astype(str) df['amount'] = df['date_str'].map(lambda d: supplement.get(d, {}).get('amount', 0)) df['turnover'] = df['date_str'].map(lambda d: supplement.get(d, {}).get('turnover', 0)) df = df.drop(columns=['date_str']) else: df['amount'] = 0.0 df['turnover'] = 0.0 return df def get_fund_flow_data(ts_code: str, days=65) -> pd.DataFrame: """ 获取个股历史资金流向数据 优先级: westock-data → 东方财富 → AKShare (新浪跳过) Returns: DataFrame with columns: ['date', 'fund_net_inflow', 'fund_net_inflow_ratio'] 全部失败时返回空DataFrame """ code = ts_code.split('.')[0] market_tag = f"{'sh' if code.startswith(('6','9')) else 'sz'}{code}" # ── 第1优先: westock-data ── try: result = subprocess.run( ['westock-data', 'fund', market_tag], capture_output=True, text=True, timeout=10 ) if result.returncode == 0 and result.stdout.strip(): fund_data = json.loads(result.stdout) if fund_data and isinstance(fund_data, list): rows = [] for item in fund_data[-days:]: rows.append({ 'date': str(item.get('date', '')), 'fund_net_inflow': float(item.get('main_net_inflow', item.get('net_inflow', 0))), 'fund_net_inflow_ratio': float(item.get('main_net_inflow_ratio', item.get('net_inflow_ratio', 0))), }) if rows: return pd.DataFrame(rows) except Exception: pass # ── 第2优先: 新浪(跳过 - 不包含资金流向数据) ── # ── 第3优先: 东方财富 ── try: import requests as _req secid = f"0.{code}" if code.startswith(('000','002','003','300')) else f"1.{code}" url = (f"https://push2.eastmoney.com/api/qt/stock/fflow/kline/get" f"?secid={secid}&fields1=f1,f2,f3,f7" f"&fields2=f51,f52,f53,f54,f55" f"&klt=101&lmt={days + 30}") headers = {'User-Agent': 'Mozilla/5.0', 'Referer': 'https://quote.eastmoney.com/'} resp = _req.get(url, headers=headers, timeout=8) data = resp.json() if data and 'data' in data and 'klines' in data['data']: rows = [] for line in data['data']['klines']: parts = line.split(',') if len(parts) >= 5: rows.append({ 'date': parts[0], 'fund_net_inflow': float(parts[2]) if parts[2] else 0, 'fund_net_inflow_ratio': float(parts[3]) if parts[3] else 0, }) if rows: df_ret = pd.DataFrame(rows) return df_ret.tail(days).reset_index(drop=True) except Exception: pass # ── 第4优先: AKShare ── try: market = "sh" if code.startswith(('6','9')) else "sz" df_ak = ak.stock_individual_fund_flow(stock=code, market=market) df_ak = df_ak.rename(columns={ '日期': 'date', '主力净流入净额': 'fund_net_inflow', '主力净流入占比': 'fund_net_inflow_ratio' }) df_ak['fund_net_inflow'] = df_ak['fund_net_inflow'].fillna(0) df_ak['fund_net_inflow_ratio'] = df_ak['fund_net_inflow_ratio'].fillna(0.0) df_ak = df_ak.tail(days) return df_ak[['date', 'fund_net_inflow', 'fund_net_inflow_ratio']] except Exception: pass # ── 全部失败 → 返回空DataFrame ── return pd.DataFrame(columns=['date', 'fund_net_inflow', 'fund_net_inflow_ratio']) def get_chip_data(ts_code: str) -> dict: """ 获取个股筹码数据(日级截面数据) 优先级: westock-data → 东方财富 (新浪/AKShare跳过) Returns: { 'profit_ratio': float, 'chip_concentration': float } 全部失败时返回 None,降级使用近似估算 """ code = ts_code.split('.')[0] market_tag = f"{'sh' if code.startswith(('6','9')) else 'sz'}{code}" # ── 第1优先: westock-data ── try: result = subprocess.run( ['westock-data', 'chip', market_tag], capture_output=True, text=True, timeout=10 ) if result.returncode == 0 and result.stdout.strip(): chip = json.loads(result.stdout) if chip and isinstance(chip, dict): return { 'profit_ratio': float(chip.get('profit_ratio', chip.get('profitRatio', 0.5))), 'chip_concentration': float(chip.get('concentration', chip.get('chipConc', 0.5))), } except Exception: pass # ── 第2优先: 新浪(跳过 - 不包含筹码分布数据) ── # ── 第3优先: 东方财富 ── try: import requests as _req secid = f"0.{code}" if code.startswith(('000','002','003','300')) else f"1.{code}" url = f"https://push2.eastmoney.com/api/qt/stock/chip/get?secid={secid}" headers = {'User-Agent': 'Mozilla/5.0', 'Referer': 'https://quote.eastmoney.com/'} resp = _req.get(url, headers=headers, timeout=8) data = resp.json() if data and 'data' in data: d = data['data'] return { 'profit_ratio': float(d.get('profitRatio', d.get('profit_ratio', 0.5))) / 100, 'chip_concentration': float(d.get('chipConc', d.get('concentration', 0.5))) / 100, } except Exception: pass # ── 第4优先: AKShare(跳过 - 无统一筹码分布API) ── return None def _classify_news_sentiment(title: str) -> str: """新闻多空分类""" if any(kw in title for kw in ['涨', '增', '利好', '突破', '涨停', '强势', '牛']): return 'bullish' elif any(kw in title for kw in ['跌', '减', '利空', '风险', '跌停', '预警', '崩']): return 'bearish' return 'neutral' def fetch_stock_news(stock_name: str, max_items=10) -> list: """ 搜索股票相关新闻 优先级: westock-data → 新浪搜索 → 东方财富搜索 (AKShare跳过) 环境变量: - SKIP_STOCK_NEWS=1: 跳过新闻抓取,避免推荐接口被外部新闻源拖慢 - STOCK_NEWS_TIMEOUT: 单个新闻源请求超时时间,默认 3 秒 返回: [{title, url, source, signal}, ...] """ if os.getenv('SKIP_STOCK_NEWS', '0').lower() in ('1', 'true', 'yes', 'on'): return [] try: news_timeout = float(os.getenv('STOCK_NEWS_TIMEOUT', '3')) except Exception: news_timeout = 3.0 news_list = [] # ── 第1优先: westock-data ── try: result = subprocess.run( ['westock-data', 'news', stock_name, '--limit', str(max_items)], capture_output=True, text=True, timeout=10 ) if result.returncode == 0 and result.stdout.strip(): items = json.loads(result.stdout) if items and isinstance(items, list): for item in items[:max_items]: title = item.get('title', '') if title: news_list.append({ 'title': title, 'url': item.get('url', ''), 'source': item.get('source', 'westock'), 'signal': _classify_news_sentiment(title), }) except Exception: pass # ── 第2优先: 新浪搜索 ── if len(news_list) < max_items: try: import requests as _req headers_ua = {'User-Agent': 'Mozilla/5.0', 'Referer': 'https://finance.sina.com.cn/'} search_url = f'https://search.sina.com.cn/news?q={stock_name}&range=title&c=news&sort=time' sr = _req.get(search_url, headers=headers_ua, timeout=(2, news_timeout)) sr.encoding = 'utf-8' items = re.findall( r'

]*target="_blank">(.*?)

', sr.text, re.DOTALL ) for url, title in items[:max_items - len(news_list)]: clean_title = re.sub(r'<[^>]+>', '', title).strip() if clean_title: news_list.append({ 'title': clean_title, 'url': url, 'source': '新浪财经', 'signal': _classify_news_sentiment(clean_title), }) except Exception: pass # ── 第3优先: 东方财富搜索 ── if len(news_list) < max_items: try: import requests as _req em_url = (f'https://search-api-web.eastmoney.com/search/jsonp' f'?param=%7B%22uid%22%3A%22%22%2C%22keyword%22%3A%22{stock_name}' f'%22%2C%22type%22%3A%5B%22cmsArticleWebOld%22%5D%7D') headers_ua = {'User-Agent': 'Mozilla/5.0', 'Referer': 'https://www.eastmoney.com/'} em_r = _req.get(em_url, headers=headers_ua, timeout=(2, news_timeout)) em_match = re.search(r'jQuery\((.+)\)', em_r.text) if em_match: em_data = json.loads(em_match.group(1)) for article in em_data.get('data', [])[:max_items - len(news_list)]: title = article.get('title', '') if title: news_list.append({ 'title': title, 'url': article.get('url', ''), 'source': '东方财富', 'signal': _classify_news_sentiment(title), }) except Exception: pass # ── 第4优先: AKShare(跳过 - 无通用个股新闻搜索API) ── return news_list def calc_macd(df: pd.DataFrame) -> pd.DataFrame: """MACD指标 (EMA12-26-9)""" df = df.copy() ema_fast = df['close'].ewm(span=12, adjust=False).mean() ema_slow = df['close'].ewm(span=26, adjust=False).mean() df['macd_dif'] = ema_fast - ema_slow df['macd_dea'] = df['macd_dif'].ewm(span=9, adjust=False).mean() df['macd_bar'] = 2 * (df['macd_dif'] - df['macd_dea']) return df def calc_kdj(df: pd.DataFrame) -> pd.DataFrame: """KDJ指标 (9,3,3)""" df = df.copy() low_min = df['low'].rolling(9).min() high_max = df['high'].rolling(9).max() rsv = (df['close'] - low_min) / (high_max - low_min) * 100 rsv = rsv.fillna(50) df['kdj_k'] = rsv.ewm(com=2, adjust=False).mean() df['kdj_d'] = df['kdj_k'].ewm(com=2, adjust=False).mean() df['kdj_j'] = 3 * df['kdj_k'] - 2 * df['kdj_d'] return df def calc_rsi(df: pd.DataFrame, period=14) -> pd.DataFrame: """RSI指标""" df = df.copy() delta = df['close'].diff() gain = delta.where(delta > 0, 0.0) loss = (-delta).where(delta < 0, 0.0) avg_gain = gain.ewm(span=period, adjust=False).mean() avg_loss = loss.ewm(span=period, adjust=False).mean() # 处理边界情况:纯涨(RSI=100) / 纯跌(RSI=0) / 横盘(RSI=50) cond_up = (avg_gain > 0) & (avg_loss == 0) cond_down = (avg_gain == 0) & (avg_loss > 0) cond_flat = (avg_gain == 0) & (avg_loss == 0) rs = avg_gain / avg_loss.replace(0, float('inf')) df['rsi14'] = 100 - (100 / (1 + rs)) df['rsi14'] = df['rsi14'].where(~cond_up, 100.0) df['rsi14'] = df['rsi14'].where(~cond_down, 0.0) df['rsi14'] = df['rsi14'].where(~cond_flat, 50.0) return df def calculate_indicators(df: pd.DataFrame): """计算全部技术指标(MA/BOLL/MACD/KDJ/RSI/量比/极值)""" df = df.copy() # 原有均线+布林带 df['ma5'] = df['close'].rolling(5).mean().round(2) df['ma10'] = df['close'].rolling(10).mean().round(2) df['ma20'] = df['close'].rolling(20).mean().round(2) df['ma60'] = df['close'].rolling(60).mean().round(2) df['std20'] = df['close'].rolling(20).std() df['boll_u'] = (df['ma20'] + 2 * df['std20']).round(2) df['boll_m'] = df['ma20'].round(2) df['boll_l'] = (df['ma20'] - 2 * df['std20']).round(2) # 新增技术指标 df = calc_macd(df) df = calc_kdj(df) df = calc_rsi(df) # 新增量比和极值 df['vol_ratio'] = df['vol_w'] / df['vol_w'].rolling(20).mean() df['high_20'] = df['high'].rolling(20).max() df['low_20'] = df['low'].rolling(20).min() df['high_60'] = df['high'].rolling(60).max() df['low_60'] = df['low'].rolling(60).min() return df def find_high_volume_days(df: pd.DataFrame, lookback=20): """识别高量日""" avg20 = df.tail(lookback)['vol_w'].mean() high_days = [] for i in range(len(df)): r = df.iloc[i] prev3 = df.iloc[max(0, i-3):i] prev_max = prev3['vol_w'].max() if len(prev3) > 0 else 0 if r['vol_w'] > prev_max and r['vol_w'] > avg20 * 0.8: high_days.append({ 'date': r['date'], 'close': r['close'], 'pct': r['pct'], 'vol_w': r['vol_w'], 'prev3_max': round(prev_max, 0), 'is_high': True }) elif i >= len(df) - 10: high_days.append({ 'date': r['date'], 'close': r['close'], 'pct': r['pct'], 'vol_w': r['vol_w'], 'prev3_max': round(prev_max, 0), 'is_high': False }) return high_days, avg20 # ==================== 新增规则函数(P0批次:数据已有) ==================== def _rule_01_bottom_volume(df, latest): """规则01: 底部放量 — 60日低位20%内 + 量>5日均量×1.5""" low_60 = df['low'].min() high_60 = df['high'].max() price_pos = (latest['close'] - low_60) / (high_60 - low_60) if high_60 > low_60 else 0.5 vol_ma5 = df.tail(5)['vol_w'].mean() if price_pos < 0.2 and vol_ma5 > 0 and latest['vol_w'] > vol_ma5 * 1.5: return {'signal': '🟢', 'desc': f'底部放量(价格处于60日低位{price_pos*100:.0f}%,量能放大)'} return None def _rule_03_break_platform(df, latest): """规则03: 放量突破平台 — 横盘20日振幅<10% + 放量1.5倍突破20日最高""" if len(df) < 20: return None d20 = df.tail(20) amplitude = (d20['high'].max() - d20['low'].min()) / d20['low'].min() if d20['low'].min() > 0 else 0 vol_ma20 = d20['vol_w'].mean() high_20 = d20['high'].max() if amplitude < 0.10 and latest['close'] > high_20 and vol_ma20 > 0 and latest['vol_w'] > vol_ma20 * 1.5: return {'signal': '🟢', 'desc': f'放量突破20日平台{high_20:.2f}元,涨幅{latest["pct"]:.2f}%'} return None def _rule_04_break_ma60(df, latest): """规则04: 放量突破MA60压制 — 此前10日在MA60下方 + 当日放量站上MA60""" if len(df) < 10: return None d10 = df.tail(10) below_ma60 = all(d10.iloc[:-1]['close'] < d10.iloc[:-1]['ma60']) vol_ma20 = df.tail(20)['vol_w'].mean() if below_ma60 and latest['close'] > latest['ma60'] * 1.01 and vol_ma20 > 0 and latest['vol_w'] > vol_ma20 * 1.3: return {'signal': '🟢', 'desc': f'放量突破MA60({latest["ma60"]:.2f})压制,趋势转多'} return None def _rule_05_shrink_backtest(df, latest): """规则05: 缩量回踩不破 — 前5日有放量阳线 + 缩量回踩MA20不破""" if len(df) < 10: return None d5 = df.tail(6).iloc[:-1] vol_ma20 = df.tail(20)['vol_w'].mean() has_volume_up = any( d5.iloc[i]['vol_w'] > vol_ma20 * 1.5 and d5.iloc[i]['close'] > d5.iloc[i]['open'] for i in range(len(d5)) ) vol_shrink = latest['vol_w'] < vol_ma20 * 0.6 if vol_ma20 > 0 else False if has_volume_up and vol_shrink and latest['close'] > latest['ma20'] * 0.99: return {'signal': '🟢', 'desc': f'缩量回踩MA20({latest["ma20"]:.2f})不破,回踩有效'} return None def _rule_06_doji_bottom(df, latest): """规则06: 底部缩量十字星 — 低位十字星+极缩量""" body = abs(latest['close'] - latest['open']) total = latest['high'] - latest['low'] low_60 = df['low'].min() high_60 = df['high'].max() price_pos = (latest['close'] - low_60) / (high_60 - low_60) if high_60 > low_60 else 0.5 vol_ma20 = df.tail(20)['vol_w'].mean() if total > 0 and body / total < 0.1 and (latest['high'] - latest['low']) / latest['low'] < 0.03: if price_pos < 0.3 and latest['vol_w'] < vol_ma20 * 0.5: return {'signal': '🟢', 'desc': '底部缩量十字星,变盘前兆信号'} return None def _rule_21_bullish_ma(df, latest): """规则21: 均线多头排列 — MA5 > MA10 > MA20 > MA60""" if all(pd.notna(x) for x in [latest['ma5'], latest['ma10'], latest['ma20'], latest['ma60']]): if latest['ma5'] > latest['ma10'] > latest['ma20'] > latest['ma60']: return {'signal': '🟢', 'desc': f'均线多头排列(MA5>{latest["ma5"]:.2f} > MA10>{latest["ma10"]:.2f} > MA20>{latest["ma20"]:.2f} > MA60>{latest["ma60"]:.2f})'} return None def _rule_22_bearish_ma(df, latest): """规则22: 均线空头排列 — MA5 < MA10 < MA20 < MA60""" if all(pd.notna(x) for x in [latest['ma5'], latest['ma10'], latest['ma20'], latest['ma60']]): if latest['ma5'] < latest['ma10'] < latest['ma20'] < latest['ma60']: return {'signal': '🔴', 'desc': '均线空头排列,趋势偏空'} return None def _rule_23_golden_cross(df, latest): """规则23: 金叉 — MA5上穿MA10""" if len(df) >= 3: prev_r = df.iloc[-3] if prev_r['ma5'] <= prev_r['ma10'] and latest['ma5'] > latest['ma10']: return {'signal': '🟢', 'desc': f'MA5({latest["ma5"]:.2f})上穿MA10({latest["ma10"]:.2f}),金叉信号'} return None def _rule_27_bottom_fracture(df, latest): """规则27: 底分型 — 中间K线最低价最低,第三根收阳""" if len(df) >= 3: d1, d2, d3 = df.iloc[-3], df.iloc[-2], df.iloc[-1] if d2['low'] < d1['low'] and d2['low'] < d3['low'] and d3['close'] > d2['close']: return {'signal': '🟢', 'desc': '底分型形成,短期反转信号'} return None def _rule_36_boll_upper(df, latest): """规则36: BOLL突破上轨 — 超买信号""" if pd.notna(latest['boll_u']) and latest['close'] > latest['boll_u']: return {'signal': '🟡', 'desc': f'突破布林上轨({latest["boll_u"]:.2f}),超买注意回调'} return None def _rule_37_boll_lower(df, latest): """规则37: BOLL跌破下轨 — 超卖信号""" if pd.notna(latest['boll_l']) and latest['close'] < latest['boll_l']: return {'signal': '🟢', 'desc': f'跌破布林下轨({latest["boll_l"]:.2f}),超卖关注反弹'} return None def _rule_38_boll_shrink(df, latest): """规则38: BOLL收口 — 带宽缩窄至5%以内,变盘信号""" if pd.notna(latest['boll_u']) and pd.notna(latest['boll_l']) and pd.notna(latest['ma20']) and latest['ma20'] > 0: bandwidth = (latest['boll_u'] - latest['boll_l']) / latest['ma20'] if bandwidth < 0.05: return {'signal': '🟡', 'desc': f'布林收口(带宽{bandwidth*100:.1f}%),变盘在即'} return None # ==================== 新增规则函数(P1批次:需指标扩充后生效) ==================== def _rule_11_12_high_vol_candle(df, latest, recent_highs): """规则11/12: 高量阳线(建仓) / 高量阴线(出货)""" if not recent_highs: return None last_high = recent_highs[-1] hi_idx = df[df['date'] == last_high['date']].index if len(hi_idx) == 0: return None row = df.iloc[hi_idx[0]] if row['close'] > row['open']: return {'signal': '🟢', 'desc': f'{row["date"]}高量阳线,主力建仓形态'} else: return {'signal': '🔴', 'desc': f'{row["date"]}高量阴线,主力出货形态'} def _rule_13_staircase_volume_up(df, latest): """规则13: 连续梯量上涨 — 5日量能递增+价格上涨""" if len(df) < 5: return None d5 = df.tail(5) vol_inc = all(d5.iloc[-i]['vol_w'] > d5.iloc[-i-1]['vol_w'] for i in range(1, 5)) price_up = all(d5.iloc[-i]['close'] > d5.iloc[-i-1]['close'] for i in range(1, 5)) if vol_inc and price_up: return {'signal': '🟢🟢', 'desc': '连续5日梯量上涨,主力持续进攻'} return None def _rule_14_staircase_volume_down(df, latest): """规则14: 递减梯量 — 5日量能递减""" if len(df) < 5: return None d5 = df.tail(5) vol_dec = all(d5.iloc[-i]['vol_w'] < d5.iloc[-i-1]['vol_w'] for i in range(1, 5)) if vol_dec: return {'signal': '🔴', 'desc': '连续5日量能递减,上涨乏力'} return None def _rule_16_ground_volume(df, latest): """规则16: 地量地价 — 量创60日新低+价近60日最低""" if len(df) < 60: return None d60 = df.tail(60) if latest['vol_w'] <= d60['vol_w'].min() * 1.05: low_60 = d60['low'].min() if latest['close'] <= low_60 * 1.02: return {'signal': '🟢', 'desc': f'地量地价(量创60日新低,价在低位),底部确认信号'} return None def _rule_17_volume_price_up(df, latest): """规则17: 量价齐升 — 连续3日量增价涨""" if len(df) < 3: return None d3 = df.tail(4) if all(d3.iloc[-i]['close'] > d3.iloc[-i-1]['close'] and d3.iloc[-i]['vol_w'] > d3.iloc[-i-1]['vol_w'] for i in range(1, 3)): return {'signal': '🟢', 'desc': '连续3日量价齐升,健康上升趋势'} return None def _rule_19_price_down_vol_up(df, latest): """规则19: 价跌量增 — 恐慌抛售""" vol_ma20 = df.tail(20)['vol_w'].mean() if latest['pct'] < -2 and vol_ma20 > 0 and latest['vol_w'] > vol_ma20 * 1.5: return {'signal': '🔴', 'desc': f'价跌量增(跌{latest["pct"]:.2f}%),恐慌抛售'} return None def _rule_20_price_down_vol_shrink(df, latest): """规则20: 价跌量缩 — 下跌动能减弱""" vol_ma20 = df.tail(20)['vol_w'].mean() if latest['pct'] < 0 and vol_ma20 > 0 and latest['vol_w'] < vol_ma20 * 0.6: return {'signal': '🟢', 'desc': '价跌量缩,下跌动能减弱'} return None def _rule_29_macd_golden_cross(df, latest): """规则29: MACD金叉 — DIF上穿DEA""" if len(df) >= 3 and 'macd_dif' in df.columns and 'macd_dea' in df.columns: prev_dif = df.iloc[-3]['macd_dif'] prev_dea = df.iloc[-3]['macd_dea'] if prev_dif <= prev_dea and latest['macd_dif'] > latest['macd_dea']: return {'signal': '🟢', 'desc': f'MACD金叉(DIF={latest["macd_dif"]:.4f},DEA={latest["macd_dea"]:.4f})'} return None def _rule_30_macd_dead_cross(df, latest): """规则30: MACD死叉 — DIF下穿DEA""" if len(df) >= 3 and 'macd_dif' in df.columns and 'macd_dea' in df.columns: prev_dif = df.iloc[-3]['macd_dif'] prev_dea = df.iloc[-3]['macd_dea'] if prev_dif >= prev_dea and latest['macd_dif'] < latest['macd_dea']: return {'signal': '🔴', 'desc': f'MACD死叉(DIF={latest["macd_dif"]:.4f})'} return None def _rule_31_macd_top_divergence(df, latest): """规则31: MACD顶背离 — 价格新高但DIF未新高""" if len(df) >= 30 and 'macd_dif' in df.columns: d30 = df.tail(30) price_high = latest['close'] >= d30['close'].max() * 0.99 macd_high = d30['macd_dif'].max() recent_macd = d30.tail(5)['macd_dif'].max() if price_high and recent_macd < macd_high * 0.95: return {'signal': '🔴', 'desc': 'MACD顶背离(价格新高但DIF未新高),回调风险'} return None def _rule_32_macd_bottom_divergence(df, latest): """规则32: MACD底背离 — 价格新低但DIF未新低""" if len(df) >= 30 and 'macd_dif' in df.columns: d30 = df.tail(30) price_low = latest['close'] <= d30['close'].min() * 1.01 macd_low = d30['macd_dif'].min() recent_macd = d30.tail(5)['macd_dif'].min() if price_low and recent_macd > macd_low * 0.95: return {'signal': '🟢', 'desc': 'MACD底背离(价格新低但DIF未新低),反弹机会'} return None # ==================== 新增规则函数(P2批次:需新数据源激活) ==================== def _rule_08_high_vol_next_shrink(df, latest, recent_highs): """规则08: 高量次日缩量 — 次日量<高量日60%""" if not recent_highs or len(df) < 2: return None last_high = recent_highs[-1] hi_idx = df[df['date'] == last_high['date']].index if len(hi_idx) == 0 or hi_idx[0] + 1 >= len(df): return None next_row = df.iloc[hi_idx[0] + 1] if next_row['vol_w'] < last_high['vol_w'] * 0.6: return {'signal': '🟡', 'desc': '高量次日缩量60%,主力锁仓/出货暂歇'} return None def _rule_09_high_vol_continuous_shrink(df, latest, recent_highs): """规则09: 高量后连续缩量 — 3日以上缩量窄幅震荡""" if not recent_highs: return None last_high = recent_highs[-1] hi_idx = df[df['date'] == last_high['date']].index if len(hi_idx) == 0: return None after = df.iloc[hi_idx[0]+1:] if len(after) < 3: return None vol_ma20 = df.tail(20)['vol_w'].mean() all_shrink = all(after.iloc[i]['vol_w'] < vol_ma20 for i in range(3)) narrow_range = (after['high'].max() - after['low'].min()) / after['low'].min() < 0.03 if all_shrink and narrow_range: return {'signal': '🟡', 'desc': f'高量后连续3日缩量窄幅震荡'} return None def _rule_10_high_vol_retest(df, latest, recent_highs): """规则10: 高量突破后回踩确认 — 缩量回踩压力位不破""" if not recent_highs: return None last_high = recent_highs[-1] hi_idx = df[df['date'] == last_high['date']].index if len(hi_idx) == 0: return None hi_pos = hi_idx[0] after = df.iloc[hi_pos+1:] if len(after) < 3: return None pressure = df.iloc[hi_pos]['high'] retest_low = after.tail(3)['low'].min() vol_ma20 = df.tail(20)['vol_w'].mean() if retest_low > pressure * 0.97 and after.tail(3)['vol_w'].mean() < vol_ma20 * 0.7: return {'signal': '🟢', 'desc': f'高量突破后缩量回踩{retest_low:.2f}(压力{pressure:.2f}),回踩确认有效'} return None def _rule_15_sky_volume_sky_price(df, latest): """规则15: 天量天价 — 量创60日新高+价创60日新高+长上影线""" if len(df) < 60: return None d60 = df.tail(60) vol_ma60 = d60['vol_w'].mean() high_60 = d60['high'].max() vol_new_high = latest['vol_w'] > vol_ma60 * 2.5 price_new_high = latest['close'] > high_60 * 0.95 body = abs(latest['close'] - latest['open']) upper_shadow = latest['high'] - max(latest['close'], latest['open']) long_upper = upper_shadow > body * 2 and body > 0 if vol_new_high and price_new_high and long_upper: return {'signal': '🔴', 'desc': f'天量天价(量比{latest["vol_w"]/vol_ma60:.1f}倍),见顶信号'} return None def _rule_18_price_up_vol_down(df, latest): """规则18: 价涨量缩背离 — 3日上涨但量递减+J值>100""" if len(df) < 4: return None d4 = df.tail(4) prices_up = all(d4.iloc[-i]['close'] > d4.iloc[-i-1]['close'] for i in range(1, 3)) if not prices_up: return None vols = [d4.iloc[-i]['vol_w'] for i in range(1, 4)] vol_decreasing = all(vols[i] < vols[i-1] for i in range(1, len(vols))) if vol_decreasing and 'kdj_j' in latest and latest['kdj_j'] > 100: return {'signal': '🟡', 'desc': f'上涨缩量背离+J值{latest["kdj_j"]:.1f}>100,回调预警'} return None def analyze_rules(df: pd.DataFrame, latest_close: float, avg20_vol: float, high_days: list) -> dict: """分析全部规则,返回触发结果""" results = {} latest = df.iloc[-1] d10 = df.tail(10) # 高量相关统计 high_count_10d = sum(1 for h in high_days if h['is_high'] and h['date'] >= d10.iloc[0]['date']) consecutive_high = 0 for h in reversed(high_days): if h['is_high'] and h['date'] >= d10.iloc[-3]['date']: consecutive_high += 1 else: break recent_highs = [h for h in high_days if h['is_high']] # ── 原有已实现规则 ── # 规则02: 高量出现 if high_count_10d > 0: results['规则02'] = {'signal': '🟡', 'desc': f'10日内出现{high_count_10d}次高量(主力异动)'} # 规则07: 高量后3天定性 if high_count_10d > 0: results['规则07'] = {'signal': '🟡', 'desc': '高量后需3天持续跟踪确认方向'} # 规则24/28: 高量突破上影线 if len(recent_highs) >= 1: last_high = recent_highs[-1] hi_idx = df[df['date'] == last_high['date']].index if len(hi_idx) > 0: row = df.iloc[hi_idx[0]] shadow_high = row['high'] if latest_close > shadow_high: results['规则24'] = {'signal': '🟢', 'desc': f'突破高量上影线{shadow_high}元,确认看多'} results['规则28'] = {'signal': '🟢🟢', 'desc': f'高量阳线实体突破前高{shadow_high},重仓信号'} # 规则25: 高量后高低点下移 if len(df) >= 5: last5 = df.tail(5) if last5['high'].iloc[-1] <= last5['high'].iloc[-2] and last5['low'].iloc[-1] <= last5['low'].iloc[-2]: results['规则25'] = {'signal': '🔴', 'desc': '高量后连续5天高低点下移,减仓信号'} # 规则33: 累计多次高量 if high_count_10d >= 3: results['规则33'] = {'signal': '🟠', 'desc': f'10日内{high_count_10d}次间断高量,顶部预警'} # 规则34: 梯量形态 if consecutive_high >= 3: results['规则34'] = {'signal': '🟡', 'desc': f'连续{consecutive_high}天高量(梯量),警惕趋势反转'} # 规则35: 高量后支撑守住 if len(recent_highs) > 0: support = min(df[df['date'] >= recent_highs[-1]['date']].tail(3)['low'].min(), latest_close) if latest_close > support * 0.97: results['规则35'] = {'signal': '🟢', 'desc': f'守住{support:.2f}元支撑,防御性持有'} # 规则26: 顶分型 if len(df) >= 3: last3 = df.tail(3) if last3.iloc[-1]['close'] < last3.iloc[-2]['close'] and last3.iloc[-2]['close'] > last3.iloc[-1]['close']: results['规则26'] = {'signal': '🔴', 'desc': '形成顶分型,短期压力,减仓'} # ── P0批次新增规则(调用独立函数) ── for rule_fn in [ _rule_01_bottom_volume, _rule_03_break_platform, _rule_04_break_ma60, _rule_05_shrink_backtest, _rule_06_doji_bottom, _rule_21_bullish_ma, _rule_22_bearish_ma, _rule_23_golden_cross, _rule_27_bottom_fracture, _rule_36_boll_upper, _rule_37_boll_lower, _rule_38_boll_shrink, ]: result = rule_fn(df, latest) if result: name = rule_fn.__name__.replace('_rule_', '规则').replace('_', '/') results[name] = result # ── P1批次新增规则(需指标扩充后生效) ── for rule_fn in [ _rule_11_12_high_vol_candle, _rule_13_staircase_volume_up, _rule_14_staircase_volume_down, _rule_16_ground_volume, _rule_17_volume_price_up, _rule_19_price_down_vol_up, _rule_20_price_down_vol_shrink, _rule_29_macd_golden_cross, _rule_30_macd_dead_cross, _rule_31_macd_top_divergence, _rule_32_macd_bottom_divergence, ]: args = (df, latest) if 'recent_highs' in rule_fn.__code__.co_varnames[:rule_fn.__code__.co_argcount]: args = (df, latest, recent_highs) result = rule_fn(*args) if result: name = rule_fn.__name__.replace('_rule_', '规则').replace('_', '/') results[name] = result # ── P2批次新增规则 ── for rule_fn in [ _rule_08_high_vol_next_shrink, _rule_09_high_vol_continuous_shrink, _rule_10_high_vol_retest, _rule_15_sky_volume_sky_price, _rule_18_price_up_vol_down, ]: args = (df, latest) if 'recent_highs' in rule_fn.__code__.co_varnames[:rule_fn.__code__.co_argcount]: args = (df, latest, recent_highs) result = rule_fn(*args) if result: name = rule_fn.__name__.replace('_rule_', '规则').replace('_', '/') results[name] = result return results # ==================== 资讯规则分析 ==================== # 资讯关键词映射 NEWS_KEYWORDS = { 'bullish': [ '利好', '上涨', '突破', '看好', '增持', '推荐买入', '业绩增长', '订单', '合作', '政策支持', '补贴', '获批', '中标', '产能扩张', '出口', '需求增长', '景气', '地缘缓和', '降息', '放水', '宽松' ], 'bearish': [ '利空', '下跌', '减持', '看空', '业绩下滑', '亏损', '风险', '调查', '处罚', '政策收紧', '加息', '缩表', '制裁', '出口受限', '竞争加剧', '产能过剩', '地缘紧张', '战争', '冲突', '贸易战' ], 'sector_positive': { 'AI': ['人工智能', 'AI', '大模型', '算力', '芯片', '半导体'], '半导体': ['半导体', '芯片', '集成电路', '晶圆', '光刻', '国产替代'], '新能源': ['新能源', '锂电', '光伏', '储能', '电动车', '电池', '风电'], '医药': ['医药', '医疗', '生物', '疫苗', '创新药', '器械'], '消费': ['消费', '食品', '饮料', '家电', '零售', '旅游', '酒店'], '金融': ['银行', '保险', '证券', '券商', '信托', '金融科技'], }, } def analyze_news_sentiment(stock_name: str, news_items: list = None) -> dict: """分析股票相关资讯情绪 Args: stock_name: 股票名称 news_items: 资讯列表,格式 [{title, signal, ...}, ...] 如果为None,则返回中性结果 Returns: dict: { 'rule_name': '规则39', 'signal': '🟢'/'🟡'/'🔴', 'desc': 描述, 'news_count': 相关资讯数量, 'sentiment': 'positive'/'negative'/'neutral' } """ if not news_items or len(news_items) == 0: return { 'rule_name': '规则39', 'signal': '🟡', 'desc': '暂无相关资讯,保持观望', 'news_count': 0, 'sentiment': 'neutral' } bullish_count = 0 bearish_count = 0 matched_news = [] for item in news_items: title = (item.get('title') or '').lower() # 检查利好关键词 for kw in NEWS_KEYWORDS['bullish']: if kw.lower() in title: bullish_count += 1 matched_news.append({'title': item.get('title', ''), 'type': '利好'}) break # 检查利空关键词 for kw in NEWS_KEYWORDS['bearish']: if kw.lower() in title: bearish_count += 1 matched_news.append({'title': item.get('title', ''), 'type': '利空'}) break if bullish_count > bearish_count * 1.5 and bullish_count >= 2: sentiment = 'positive' signal = '🟢' desc = f'资讯面偏多({bullish_count}条利好 vs {bearish_count}条利空),关注机会' elif bearish_count > bullish_count * 1.5 and bearish_count >= 2: sentiment = 'negative' signal = '🔴' desc = f'资讯面偏空({bearish_count}条利空 vs {bullish_count}条利好),风险警惕' elif bullish_count > bearish_count: sentiment = 'positive' signal = '🟡' desc = f'资讯面略偏多({bullish_count}利好 vs {bearish_count}利空),谨慎关注' elif bearish_count > bullish_count: sentiment = 'negative' signal = '🟡' desc = f'资讯面略偏空({bearish_count}利空 vs {bullish_count}利好),保持警觉' else: sentiment = 'neutral' signal = '🟡' desc = f'资讯面中性({len(news_items)}条资讯),跟随量价信号' return { 'rule_name': '规则39', 'signal': signal, 'desc': desc, 'news_count': len(news_items), 'sentiment': sentiment, 'matched_news': matched_news[:3] # 最多显示3条 } def analyze_sector_news(stock_sector: str, news_items: list = None) -> dict: """分析行业板块相关资讯 Args: stock_sector: 行业板块名称 news_items: 资讯列表 Returns: dict: 规则结果 """ if not news_items or len(news_items) == 0: return None if not stock_sector: return None sector_keywords = [] for s_name, keywords in NEWS_KEYWORDS['sector_positive'].items(): if stock_sector in s_name or s_name in stock_sector: sector_keywords = keywords break if not sector_keywords: return None positive_count = 0 negative_count = 0 for item in news_items: title = (item.get('title') or '').lower() for kw in sector_keywords: if kw.lower() in title: # 检查是利好还是利空 is_bullish = any(k in title for k in [l.lower() for l in NEWS_KEYWORDS['bullish']]) is_bearish = any(k in title for k in [l.lower() for l in NEWS_KEYWORDS['bearish']]) if is_bullish: positive_count += 1 elif is_bearish: negative_count += 1 break if positive_count >= 2 and positive_count > negative_count: return { 'rule_name': '规则40', 'signal': '🟢', 'desc': f'{stock_sector}板块受政策/市场利好支持,关注' } elif negative_count >= 2 and negative_count > positive_count: return { 'rule_name': '规则40', 'signal': '🔴', 'desc': f'{stock_sector}板块面临压力,注意风险' } return None def determine_signal(trigger_rules: dict) -> tuple: """综合判断信号(加权评分版 V2.1.0) 信号权重: 🟢🟢 (强烈买入) = +3 🟢 (看多) = +2 🟡 (观望) = 0 🟠 (预警) = -2 🔴 (看空) = -3 判定逻辑: score >= 5 → 买入 score >= 2 → 谨慎看多 score <= -5 → 减仓/清仓 score <= -2 → 警惕 否则 → 观望 """ weights = {'🟢🟢': 3, '🟢': 2, '🟡': 0, '🟠': -2, '🔴': -3} score = sum(weights.get(data['signal'], 0) for rule, data in trigger_rules.items()) if score >= 5: return ('买入', '🟢') elif score >= 2: return ('谨慎看多', '🟡') elif score <= -5: return ('减仓/清仓', '🔴') elif score <= -2: return ('风险警惕', '🟠') else: return ('观望', '🟡') def generate_summary(report: dict) -> str: """生成分析总结""" name = report.get('name', '') close = report.get('latest_close', 0) pct = report.get('pct_change', 0) signal = report.get('signal', '观望') ma5 = report.get('ma5', 0) ma10 = report.get('ma10', 0) ma20 = report.get('ma20', 0) boll_u = report.get('boll_upper', 0) boll_l = report.get('boll_lower', 0) boll_pct = report.get('boll_pct', 0) vol_ratio = report.get('vol_ratio', 0) high_days_count = len([h for h in report.get('high_volume_days', []) if h.get('is_high')]) lines = [ f"{name}({report.get('ts_code', '')})最新收盘 {close:.2f} 元,", f"{'上涨' if pct > 0 else '下跌'} {abs(pct):.2f}%。", f"均线系统:MA5={ma5:.2f},MA10={ma10:.2f},MA20={ma20:.2f}。", f"布林带:上轨 {boll_u:.2f},下轨 {boll_l:.2f},当前位于 {boll_pct:.1f}% 位置。", f"量能状态:量比 {vol_ratio:.2f}x,{'高于' if vol_ratio > 1 else '低于'}20日均量,", f"{'成交量活跃' if vol_ratio > 1.2 else '量能萎缩' if vol_ratio < 0.8 else '量能正常'}。", f"{'近10日出现' + str(high_days_count) + '次高量' if high_days_count > 0 else '近期无明显高量异动'}。", f"综合信号:**{signal}**。", ] return ''.join(lines) def full_analysis(ts_code_or_name: str): """执行完整量价分析""" # 解析输入 raw_input = ts_code_or_name.strip() if re.match(r'^\d{6}(\.[A-Z]{2})?$', raw_input): ts_code = raw_input.upper() if '.' not in ts_code: code = ts_code if code.startswith(('000', '002', '003', '300')): ts_code = f"{code}.SZ" elif code.startswith(('600', '601', '603', '688')): ts_code = f"{code}.SH" else: ts_code = f"{code}.SZ" else: ts_code = search_stock_by_name(raw_input) if not ts_code: return {'error': f'未找到股票:{raw_input}'} # 获取数据(V2.1.0: 增强K线含amount/turnover) df = get_augmented_kline(ts_code, days=65) df = calculate_indicators(df) latest = df.iloc[-1] prev = df.iloc[-2] if len(df) > 1 else latest d10 = df.tail(10) # V2.1.0: 获取资金流向数据并merge fund_df = get_fund_flow_data(ts_code, days=65) if not fund_df.empty: df['date_str'] = df['date'].astype(str) fund_df['date_str'] = fund_df['date'].astype(str) fund_map = fund_df.set_index('date_str')[['fund_net_inflow', 'fund_net_inflow_ratio']].to_dict('index') df['fund_net_inflow'] = df['date_str'].map(lambda d: fund_map.get(d, {}).get('fund_net_inflow', 0)) df['fund_net_inflow_ratio'] = df['date_str'].map(lambda d: fund_map.get(d, {}).get('fund_net_inflow_ratio', 0.0)) df = df.drop(columns=['date_str']) else: df['fund_net_inflow'] = 0.0 df['fund_net_inflow_ratio'] = 0.0 # 基本信息 —— 优先用 Sina 实时行情接口获取名称(快),akshare 备用 code_str = ts_code.split('.')[0] name = ts_code # 默认值 try: import requests as _req _code, _market = parse_ts_code(ts_code) _sym = f'{_market}{_code}' _headers = {'Referer': 'https://finance.sina.com.cn', 'User-Agent': 'Mozilla/5.0'} _r = _req.get(f'https://hq.sinajs.cn/list={_sym}', headers=_headers, timeout=5) _r.encoding = 'gb18030' _m = re.search(r'hq_str_\w+="([^"]+)"', _r.text) if _m and _m.group(1): _fields = _m.group(1).split(',') if _fields[0]: name = _fields[0] except Exception: pass # 若 Sina 未返回名称,再尝试 akshare(限时3秒) if name == ts_code: try: import signal as _sig spot_df = ak.stock_zh_a_spot_em() _row = spot_df[spot_df['代码'] == code_str] if not _row.empty: name = _row.iloc[0]['名称'] except Exception: pass # 计算指标 avg20 = df.tail(20)['vol_w'].mean() vol_ratio = latest['vol_w'] / avg20 if avg20 > 0 else 0 if pd.notna(latest['boll_u']) and pd.notna(latest['boll_l']) and latest['boll_u'] != latest['boll_l']: boll_pct = (latest['close'] - latest['boll_l']) / (latest['boll_u'] - latest['boll_l']) * 100 else: boll_pct = 50.0 pct_change = ((latest['close'] - prev['close']) / prev['close'] * 100) if prev['close'] > 0 else 0 # 高量分析 high_days, avg20_vol = find_high_volume_days(df) # 规则分析 trigger_rules = analyze_rules(df, latest['close'], avg20_vol, high_days) # 资讯规则分析(V2.1.0: 使用真实资讯) news_items = fetch_stock_news(name, max_items=8) news_sentiment = analyze_news_sentiment(name, news_items) trigger_rules[news_sentiment['rule_name']] = { 'signal': news_sentiment['signal'], 'desc': news_sentiment['desc'] } # 行业板块资讯分析 sector_news = analyze_sector_news(name, news_items) if sector_news: trigger_rules[sector_news['rule_name']] = { 'signal': sector_news['signal'], 'desc': sector_news['desc'] } # 综合信号 signal, signal_emoji = determine_signal(trigger_rules) # K线10日数据 kline_10d = [] for _, r in d10.iterrows(): kline_10d.append({ 'date': r['date'], 'open': round(r['open'], 2), 'high': round(r['high'], 2), 'low': round(r['low'], 2), 'close': round(r['close'], 2), 'pct': r['pct'], 'vol_w': round(r['vol_w'], 0), 'ma5': round(r['ma5'], 2) if pd.notna(r['ma5']) else None, 'ma10': round(r['ma10'], 2) if pd.notna(r['ma10']) else None, 'ma20': round(r['ma20'], 2) if pd.notna(r['ma20']) else None, }) # 组装报告 report = { 'ts_code': ts_code, 'name': name, 'created_at': datetime.now().strftime('%Y-%m-%d %H:%M'), 'latest_close': round(latest['close'], 2), 'pct_change': round(pct_change, 2), 'open': round(latest['open'], 2), 'high': round(latest['high'], 2), 'low': round(latest['low'], 2), 'vol_w': round(latest['vol_w'], 0), 'amount_bn': round(latest.get('amount', 0) / 1e8, 2), 'turnover': round(latest.get('turnover', 0), 2), 'ma5': round(latest['ma5'], 2) if pd.notna(latest['ma5']) else None, 'ma10': round(latest['ma10'], 2) if pd.notna(latest['ma10']) else None, 'ma20': round(latest['ma20'], 2) if pd.notna(latest['ma20']) else None, 'ma60': round(latest['ma60'], 2) if pd.notna(latest['ma60']) else None, 'boll_upper': round(latest['boll_u'], 2) if pd.notna(latest['boll_u']) else None, 'boll_mid': round(latest['boll_m'], 2) if pd.notna(latest['boll_m']) else None, 'boll_lower': round(latest['boll_l'], 2) if pd.notna(latest['boll_l']) else None, 'boll_pct': round(boll_pct, 1), 'macd_dif': round(latest['macd_dif'], 4) if 'macd_dif' in latest and pd.notna(latest['macd_dif']) else None, 'macd_dea': round(latest['macd_dea'], 4) if 'macd_dea' in latest and pd.notna(latest['macd_dea']) else None, 'macd_bar': round(latest['macd_bar'], 4) if 'macd_bar' in latest and pd.notna(latest['macd_bar']) else None, 'kdj_k': round(latest['kdj_k'], 2) if 'kdj_k' in latest and pd.notna(latest['kdj_k']) else None, 'kdj_d': round(latest['kdj_d'], 2) if 'kdj_d' in latest and pd.notna(latest['kdj_d']) else None, 'kdj_j': round(latest['kdj_j'], 2) if 'kdj_j' in latest and pd.notna(latest['kdj_j']) else None, 'rsi14': round(latest['rsi14'], 2) if 'rsi14' in latest and pd.notna(latest['rsi14']) else None, 'vol_ratio': round(vol_ratio, 2), 'avg20_vol': round(avg20, 0), 'high_volume_days': high_days, 'trigger_rules': trigger_rules, 'signal': signal, 'signal_emoji': signal_emoji, 'kline_10d': kline_10d, 'raw_data': df.tail(5).to_dict('records'), } report['summary'] = generate_summary(report) return report