ppanalyst / analyzer.py
petenathaphat's picture
Update analyzer.py
f23875e verified
Raw History Blame Contribute Delete
16 kB
# ===== analyzer.py (robust with Yahoo 429 guard + Stooq fallback) =====
import yfinance as yf
import numpy as np
import math, time, contextlib, re, io, csv
from zoneinfo import ZoneInfo
from functools import lru_cache
from urllib.request import urlopen, Request
PERSONA_NAME = "ที่ปรึกษาการลงทุนของคุณ"
GREETING = f"สวัสดีครับ ผม{PERSONA_NAME}"
SIGNOFF = "หากต้องการให้ผมติดตามสัญญาณต่อเนื่อง แจ้งผมได้ทุกเมื่อครับ"
CONFIG = {
"ema_fast": 12, "ema_slow": 26, "ema_signal": 9,
"ema_short_trend": 20, "ema_mid_trend": 50, "ema_long_trend": 200,
"rsi_period": 14,
"atr_period": 14,
"volume_ema_period": 20,
"sr_lookback": 240, "sr_left": 3, "sr_right": 3,
}
def fmt_num(x, d=2): return f"{x:.{d}f}" if isinstance(x,(int,float)) and math.isfinite(x) else "—"
def cap_label(x):
try:
x=float(x)
if x>=1e12: return f"{x/1e12:.2f}T"
if x>=1e9: return f"{x/1e9:.2f}B"
if x>=1e6: return f"{x/1e6:.2f}M"
return f"{x:,.0f}"
except: return "-"
def size_tag(mc):
try:
mc=float(mc)
if mc>=2e11: return " (Mega Cap)"
if mc>=1e10: return " (Large/Mid Cap)"
return " (Small Cap)"
except: return ""
def rsi_view(x):
if not (isinstance(x,(int,float)) and math.isfinite(x)): return "-"
if x >= 70: return "Overbought"
if 55 <= x < 70: return "Neutral-แรงซื้อยังดี"
if 45 <= x < 55: return "เป็นกลาง"
return "อ่อนแรง/เสี่ยงย่อ"
def ema_trend(e20, e50, e200):
ok20, ok50, ok200 = [isinstance(v,(int,float)) and math.isfinite(v) for v in (e20,e50,e200)]
if ok20 and ok50 and ok200:
if e20 > e50 > e200: return "ขาขึ้น"
if e20 > e50: return "เริ่มขาขึ้น"
return "ขาลง/Sideways"
if ok20 and ok50:
return "เริ่มขาขึ้น" if e20 > e50 else "อ่อนตัว/Sideways"
return "ข้อมูลไม่พอ"
def action_badge(action_text):
if isinstance(action_text,str) and action_text.startswith("✅"): return "BUY"
if isinstance(action_text,str) and action_text.startswith("❌"): return "AVOID"
return "WATCH"
def _first_finite_idx(arr):
idx = np.where(np.isfinite(arr))[0]
return int(idx[0]) if idx.size else None
def ema_np(arr, length):
arr = np.array(arr, dtype=float)
n = len(arr)
out = np.full(n, np.nan, dtype=float)
if length <= 1 or n == 0: return out
s0 = _first_finite_idx(arr)
if s0 is None: return out
k = 2.0/(length+1)
L = min(length, n - s0)
if L < 2: return out
seed = float(np.nanmean(arr[s0:s0+L])); out[s0+L-1] = seed
for i in range(s0+L, n):
prev = out[i-1] if math.isfinite(out[i-1]) else arr[i-1]
out[i] = (arr[i]-prev)*k + prev
return out
def rsi_wilder_np(close, period=14):
close = np.array(close, dtype=float); n = len(close)
out = np.full(n, np.nan, dtype=float)
s0 = _first_finite_idx(close)
if s0 is None or (n - s0) <= period: return out
deltas = np.diff(close)
gains = np.where(deltas>0, deltas, 0.0)
losses = np.where(deltas<0, -deltas, 0.0)
g0 = max(0, s0)
if (len(gains) - g0) < period: return out
avg_gain = np.mean(gains[g0:g0+period]); avg_loss = np.mean(losses[g0:g0+period])
rs = (avg_gain/avg_loss) if avg_loss != 0 else np.inf
out[s0+period] = 100 - 100/(1+rs)
for i in range(s0+period+1, n):
j = i-1
gain = gains[j] if j < len(gains) else 0.0
loss = losses[j] if j < len(losses) else 0.0
avg_gain = (avg_gain*(period-1)+gain)/period
avg_loss = (avg_loss*(period-1)+loss)/period
rs = (avg_gain/avg_loss) if avg_loss != 0 else np.inf
out[i] = 100 - 100/(1+rs)
return out
def macd_np(close, fast, slow, signal):
ema_fast = ema_np(close, fast); ema_slow = ema_np(close, slow)
macd_line = ema_fast - ema_slow; macd_sig = ema_np(macd_line, signal)
return macd_line, macd_sig, macd_line - macd_sig
def atr_np(high, low, close, period=14):
high = np.array(high, dtype=float); low = np.array(low, dtype=float); close= np.array(close, dtype=float)
n = len(close);
if n < 2: return np.full(n, np.nan, dtype=float)
tr = np.zeros(n); tr[0] = high[0]-low[0]
for i in range(1, n):
tr[i] = max(high[i]-low[i], abs(high[i]-close[i-1]), abs(low[i]-close[i-1]))
out = np.full(n, np.nan, dtype=float)
if n <= period: return out
out[period-1] = np.mean(tr[1:period])
for i in range(period, n): out[i] = (out[i-1]*(period-1) + tr[i]) / period
return out
def swing_pivots(high, low, lookback, left, right):
H = np.array(high, dtype=float); L = np.array(low, dtype=float)
n = len(H);
if n < left + right + 1: return [], []
start = max(0, n - lookback); sh, sl = [], []
for i in range(start + left, n - right):
if np.all(H[i] >= H[i-left:i]) and np.all(H[i] > H[i+1:i+1+right]): sh.append(H[i])
if np.all(L[i] <= L[i-left:i]) and np.all(L[i] < L[i+1:i+1+right]): sl.append(L[i])
return sl, sh
def nearest_sr(price, high, low, e50, e200):
sl, sh = swing_pivots(high, low, CONFIG["sr_lookback"], CONFIG["sr_left"], CONFIG["sr_right"])
supp = [v for v in sl if math.isfinite(v) and v < price]
resi = [v for v in sh if math.isfinite(v) and v > price]
for v in (e50, e200):
if math.isfinite(v): (supp if v < price else resi).append(v)
s = max(supp) if supp else None; r = min(resi) if resi else None
if isinstance(s,(int,float)) and isinstance(r,(int,float)) and s >= r: s, r = None, None
return s, r
def _fmt_sr(x, price):
if not (isinstance(x,(int,float)) and math.isfinite(x)): return "—"
if price >= 50: return f"{x:.0f}"
if price >= 10: return f"{x:.2f}"
return f"{x:.3f}"
# -----------------------------
# Stooq fallback (no extra deps)
# -----------------------------
def _stooq_csv_to_arrays(csv_text):
dates, open_, high, low, close, vol = [], [], [], [], [], []
r = csv.reader(io.StringIO(csv_text))
header = next(r, None) # skip header
for row in r:
if len(row) < 6:
continue
# date, open, high, low, close, volume
try:
o = float(row[1]); h = float(row[2]); l = float(row[3]); c = float(row[4])
v = float(row[5]) if row[5] not in ("", None) else np.nan
except Exception:
continue
dates.append(row[0]); open_.append(o); high.append(h); low.append(l); close.append(c); vol.append(v)
return np.array(close), np.array(high), np.array(low), np.array(vol), dates
def _fetch_from_stooq(ticker):
sym = f"{ticker.lower()}.us"
url = f"https://stooq.com/q/d/l/?s={sym}&i=d"
req = Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urlopen(req, timeout=10) as resp:
csv_text = resp.read().decode("utf-8", errors="ignore")
return _stooq_csv_to_arrays(csv_text)
# -----------------------------
# Data fetch with backoff + cache
# -----------------------------
_hist_cache = {}
def fetch_hist_enough(ticker, min_bars=120, tries=4, base_sleep=0.8):
tkr = ticker.upper()
if tkr in _hist_cache:
return _hist_cache[tkr]
# 1) Try Yahoo (yfinance) with backoff
periods = ("1y","2y","5y","max")
tk = yf.Ticker(tkr)
sleep = base_sleep
for _ in range(tries):
for p in periods:
with contextlib.suppress(Exception):
hist = tk.history(period=p, interval="1d", auto_adjust=True, progress=False)
if (hist is not None) and (not hist.empty):
_hist_cache[tkr] = hist
return hist
time.sleep(sleep)
sleep *= 2 # exponential backoff
# 2) Fallback to Stooq
with contextlib.suppress(Exception):
close, high, low, vol, dates = _fetch_from_stooq(tkr)
if close.size >= max(60, min_bars//2):
# Build a minimal DataFrame-like object using numpy structured arrays
# แต่เพื่อให้โค้ดเดิมทำงานง่าย เราจะสร้าง dict-like
import pandas as pd
df = pd.DataFrame({
"Close": close,
"High": high,
"Low": low,
"Volume": vol,
})
# index เป็น datetime (UTC naive)
df.index = pd.to_datetime(dates)
_hist_cache[tkr] = df
return df
return None
def fetch_overview(ticker):
info = {"longName": ticker.upper()}
# พยายามใช้ fast_info (เบากว่า get_info มาก)
with contextlib.suppress(Exception):
fi = yf.Ticker(ticker).fast_info
mc = getattr(fi, "market_cap", None)
if mc: info["marketCap"] = mc
# (ออปชัน) ลอง get_info แบบกัลยาณมิตร: ถ้า error/429 ก็ข้าม
with contextlib.suppress(Exception):
g = yf.Ticker(ticker).get_info()
ln = g.get("longName") or g.get("shortName")
if ln: info["longName"] = ln
pe = g.get("trailingPE")
if isinstance(pe,(int,float)): info["trailingPE"] = pe
sec = g.get("sector")
if sec: info["sector"] = sec
return info
# -----------------------------
# Classifier
# -----------------------------
def classify_action(price, e20, e50, e200, rsi_v, m_line, m_sig, m_hist, last_vol, vol_ema, n_bars):
data_ok_midlong = n_bars >= 260 and all(math.isfinite(v) for v in [e20,e50,e200])
ema_uptrend = data_ok_midlong and (e20 > e50 > e200)
ema_short_up = (math.isfinite(e20) and math.isfinite(e50) and e20 > e50)
rsi_buyzone = (math.isfinite(rsi_v) and 55 <= rsi_v <= 65)
rsi_hotzone = (math.isfinite(rsi_v) and rsi_v > 70)
macd_positive = (all(math.isfinite(v) for v in [m_line,m_sig,m_hist]) and m_line > m_sig and m_line > 0 and m_hist > 0)
above_ema50 = (math.isfinite(price) and math.isfinite(e50) and price >= e50)
vol_confirms = (math.isfinite(last_vol) and math.isfinite(vol_ema) and last_vol > vol_ema)
if (ema_uptrend or ema_short_up) and rsi_hotzone and macd_positive and above_ema50:
return "🤔 น่าสนใจ", "แข็งแรงแต่ร้อนแรง (RSI>70) — รอราคาพักตัวย่อก่อนพิจารณาครับ"
if ema_uptrend and rsi_buyzone and macd_positive and above_ema50:
return ("✅ ควรซื้อ", "Trend แข็งแรง, RSI ดี, MACD บวก และมี Volume ยืนยัน") if vol_confirms \
else ("🤔 น่าสนใจ", "สัญญาณดีมากแต่ Volume ยังไม่ยืนยัน — จับตาดูใกล้ชิด")
if ema_short_up and math.isfinite(rsi_v) and rsi_v >= 48 and macd_positive:
return "🤔 น่าสนใจ", "แนวโน้มเริ่มดี รอจังหวะย่อหรือเบรกแนวต้าน"
if (math.isfinite(e50) and math.isfinite(e200) and e50 < e200) or \
(math.isfinite(rsi_v) and rsi_v < 40) or \
(math.isfinite(m_line) and math.isfinite(m_sig) and m_line < 0 and m_line < m_sig):
return "❌ ยังไม่ควรซื้อ", "โครงสร้างยังไม่ชัด/โมเมนตัมอ่อนตัว รอสัญญาณกลับตัว"
return "🤔 น่าสนใจ", "เงื่อนไขผสมกลางๆ รอสัญญาณยืนยันเพิ่ม"
def _tidy_blocks(text: str) -> str:
t = text.strip()
t = re.sub(r"\n{3,}", "\n\n", t)
t = re.sub(r"[ \t]+\n", "\n", t)
return t
def analyze_pretty(ticker: str) -> str:
tkr = ticker.upper()
info = fetch_overview(tkr)
hist = fetch_hist_enough(tkr)
if hist is None or hist.empty:
return f"{GREETING}\n\nไม่พบข้อมูล {tkr} ครับ"
close = hist["Close"].to_numpy()
high = hist["High"].to_numpy()
low = hist["Low"].to_numpy()
vol = hist["Volume"].to_numpy() if "Volume" in hist.columns else np.full(len(close), np.nan)
n = len(close); i = -1
price = float(close[i]); prev = float(close[i-1]) if n>1 else price
chg = (price - prev) / prev * 100 if prev else 0.0
last_vol = float(vol[i]) if i < len(vol) else np.nan
e20_arr = ema_np(close, CONFIG["ema_short_trend"])
e50_arr = ema_np(close, CONFIG["ema_mid_trend"])
e200_arr= ema_np(close, CONFIG["ema_long_trend"])
rsi_arr = rsi_wilder_np(close, CONFIG["rsi_period"])
m_line, m_sig, m_hist = macd_np(close, CONFIG["ema_fast"], CONFIG["ema_slow"], CONFIG["ema_signal"])
atr_arr = atr_np(high, low, close, CONFIG["atr_period"])
vol_ema_arr = ema_np(vol, CONFIG["volume_ema_period"])
e20, e50, e200 = e20_arr[i], e50_arr[i], e200_arr[i]
rsi_v, atr, vol_ema = rsi_arr[i], atr_arr[i], vol_ema_arr[i]
m_line_v, m_sig_v, m_hist_v = m_line[i], m_sig[i], m_hist[i]
ema_state = ema_trend(e20, e50, e200)
macd_txt = ">0 ขาขึ้น" if (all(math.isfinite(v) for v in [m_line_v, m_sig_v, m_hist_v]) and m_line_v > m_sig_v and m_line_v > 0 and m_hist_v > 0) else "≤0 อ่อนแรง"
vol_txt = "สูงกว่าค่าเฉลี่ย" if (math.isfinite(last_vol) and math.isfinite(vol_ema) and last_vol > vol_ema) else "ต่ำกว่าค่าเฉลี่ย"
s, r = nearest_sr(price, high, low, e50, e200)
s_txt = _fmt_sr(s, price); r_txt = _fmt_sr(r, price)
action, why = classify_action(price, e20, e50, e200, rsi_v, m_line_v, m_sig_v, m_hist_v, last_vol, vol_ema, n)
badge = action_badge(action)
parts = []
if info.get("marketCap"): parts.append(f"Market Cap: {cap_label(info['marketCap'])}{size_tag(info['marketCap'])}")
pe = info.get("trailingPE")
if isinstance(pe,(int,float)): parts.append(f"P/E: {pe:.0f}")
if info.get("sector"): parts.append(f"Sector: {info['sector']}")
overview_line = " • ".join(parts) if parts else "-"
last_ts = hist.index[-1].to_pydatetime() if hasattr(hist.index[-1],'to_pydatetime') else None
if last_ts:
ny = last_ts.astimezone(ZoneInfo("America/New_York"))
th = last_ts.astimezone(ZoneInfo("Asia/Bangkok"))
ts_line = f"🕒 ข้อมูลอ้างอิง ณ วันที่ {ny.strftime('%Y-%m-%d')} (ตลาดสหรัฐ {ny.strftime('%H:%M %Z')}) / {th.strftime('%Y-%m-%d %H:%M')} (Asia/Bangkok)"
else:
ts_line = "🕒 ข้อมูลอ้างอิง: เวลาไม่ระบุ (แหล่งข้อมูลสำรอง)"
lines = [
f"{GREETING}",
"",
f"📊 วิเคราะห์ {tkr} ({info.get('longName', tkr)})",
"",
"💡 Overview",
f"• {overview_line}",
"",
"📈 Technical",
f"• Price: {price:,.2f} ({chg:+.1f}% วันนี้)",
f"• EMA20/50/200: {fmt_num(e20,0)} / {fmt_num(e50,0)} / {fmt_num(e200,0)} → {ema_state}",
f"• RSI(14): {fmt_num(rsi_v,1)} → {rsi_view(rsi_v)}",
f"• MACD: {macd_txt}",
f"• Volume: {vol_txt}",
f"• ATR(14): {fmt_num(atr,2)} (ความผันผวนเฉลี่ยต่อวัน)",
f"• แนวรับ: {s_txt} | แนวต้าน: {r_txt}",
"",
"📌 สรุป Action",
f"{action} → {why}",
f"🔖 ระดับสรุป: {badge}",
"",
ts_line,
"",
f"{SIGNOFF}",
]
return _tidy_blocks("\n".join(lines))