Technical Analysis of Stocks คืออะไร
Technical Analysis (TA) คือการวิเคราะห์หุ้นและสินทรัพย์ทางการเงินโดยใช้ข้อมูลราคาและปริมาณการซื้อขาย (Price & Volume) ในอดีต เพื่อคาดการณ์ทิศทางราคาในอนาคต Technical Analysis ใช้ charts, patterns, indicators และ statistical tools เป็นหลัก ต่างจาก Fundamental Analysis ที่วิเคราะห์งบการเงินและปัจจัยพื้นฐาน TA ได้รับความนิยมอย่างมากในตลาดหุ้นไทย (SET), Forex, Cryptocurrency และ Futures เนื่องจากช่วยให้ตัดสินใจซื้อขายได้อย่างเป็นระบบ
หลักการพื้นฐาน Technical Analysis
# ta_basics.py — Technical Analysis fundamentals
import json
class TABasics:
PRINCIPLES = {
"price_discounts": {
"name": "Price Discounts Everything",
"description": "ราคาสะท้อนข้อมูลทั้งหมดแล้ว (ข่าว, งบการเงิน, sentiment)",
"implication": "ดูราคาอย่างเดียวก็พอ ไม่ต้องวิเคราะห์ทุกปัจจัย",
},
"trends": {
"name": "Price Moves in Trends",
"description": "ราคาเคลื่อนไหวเป็น trend (ขึ้น, ลง, sideways)",
"implication": "Trade with the trend — ไม่สวนเทรนด์",
},
"history_repeats": {
"name": "History Tends to Repeat",
"description": "รูปแบบราคาในอดีตมักเกิดซ้ำ (chart patterns)",
"implication": "เรียนรู้ patterns เพื่อคาดการณ์อนาคต",
},
}
CHART_TYPES = {
"candlestick": {
"name": "Candlestick Chart (แท่งเทียน)",
"components": "Open, High, Low, Close (OHLC)",
"popularity": "นิยมที่สุด — ให้ข้อมูลครบในแท่งเดียว",
},
"line": {
"name": "Line Chart",
"components": "Close price only",
"popularity": "ง่าย ดู trend ภาพรวม",
},
"bar": {
"name": "Bar Chart (OHLC)",
"components": "Open, High, Low, Close",
"popularity": "คล้าย candlestick แต่ไม่มี body สี",
},
}
TIMEFRAMES = {
"scalping": {"name": "Scalping", "timeframe": "1m, 5m", "holding": "วินาที-นาที"},
"day_trading": {"name": "Day Trading", "timeframe": "15m, 1H", "holding": "ชั่วโมง (ปิดก่อนจบวัน)"},
"swing": {"name": "Swing Trading", "timeframe": "4H, Daily", "holding": "วัน-สัปดาห์"},
"position": {"name": "Position Trading", "timeframe": "Daily, Weekly", "holding": "สัปดาห์-เดือน"},
"investing": {"name": "Investing", "timeframe": "Weekly, Monthly", "holding": "เดือน-ปี"},
}
def show_principles(self):
print("=== TA Principles ===\n")
for key, p in self.PRINCIPLES.items():
print(f"[{p['name']}]")
print(f" {p['description']}")
print()
def show_charts(self):
print("=== Chart Types ===")
for key, chart in self.CHART_TYPES.items():
print(f" [{chart['name']}] {chart['components']} — {chart['popularity']}")
def show_timeframes(self):
print(f"\n=== Timeframes ===")
for key, tf in self.TIMEFRAMES.items():
print(f" [{tf['name']}] {tf['timeframe']} | Hold: {tf['holding']}")
ta = TABasics()
ta.show_principles()
ta.show_charts()
ta.show_timeframes()
Indicators ยอดนิยม
# indicators.py — Popular technical indicators
import json
import random
class TechnicalIndicators:
TREND = {
"ma": {
"name": "Moving Average (MA)",
"types": "SMA (Simple), EMA (Exponential)",
"common": "EMA 20, 50, 200",
"signal": "Price > MA = Bullish | Price < MA = Bearish | Golden Cross (50 > 200) = Strong Buy",
},
"macd": {
"name": "MACD (Moving Average Convergence Divergence)",
"components": "MACD Line (12 EMA - 26 EMA), Signal Line (9 EMA of MACD), Histogram",
"signal": "MACD > Signal = Buy | MACD < Signal = Sell | Divergence = Reversal",
},
"adx": {
"name": "ADX (Average Directional Index)",
"range": "0-100",
"signal": "ADX > 25 = Strong trend | ADX < 20 = Weak/No trend | +DI > -DI = Uptrend",
},
}
MOMENTUM = {
"rsi": {
"name": "RSI (Relative Strength Index)",
"range": "0-100",
"signal": "RSI > 70 = Overbought (อาจลง) | RSI < 30 = Oversold (อาจขึ้น) | Divergence = Reversal",
},
"stochastic": {
"name": "Stochastic Oscillator",
"range": "0-100 (%K, %D lines)",
"signal": "%K > %D = Buy | %K < %D = Sell | > 80 Overbought | < 20 Oversold",
},
}
VOLUME = {
"obv": {
"name": "OBV (On-Balance Volume)",
"description": "สะสม volume ตามทิศทางราคา",
"signal": "OBV ขึ้น + ราคาขึ้น = Confirm trend | OBV ลง + ราคาขึ้น = Divergence (อาจกลับตัว)",
},
"vwap": {
"name": "VWAP (Volume Weighted Average Price)",
"description": "ราคาเฉลี่ยถ่วงน้ำหนักด้วย volume",
"signal": "Price > VWAP = Bullish | Price < VWAP = Bearish | ใช้เป็น support/resistance",
},
}
VOLATILITY = {
"bb": {
"name": "Bollinger Bands",
"components": "Middle (SMA 20), Upper (+2 SD), Lower (-2 SD)",
"signal": "แตะ Upper = Overbought | แตะ Lower = Oversold | Squeeze = Breakout ใกล้",
},
"atr": {
"name": "ATR (Average True Range)",
"description": "วัดความผันผวนของราคา",
"signal": "ATR สูง = ผันผวนมาก | ใช้ตั้ง Stop Loss (e.g., 2× ATR)",
},
}
def show_trend(self):
print("=== Trend Indicators ===\n")
for key, ind in self.TREND.items():
print(f"[{ind['name']}]")
print(f" Signal: {ind['signal']}")
print()
def show_momentum(self):
print("=== Momentum Indicators ===")
for key, ind in self.MOMENTUM.items():
print(f" [{ind['name']}] {ind['signal']}")
def show_volume(self):
print(f"\n=== Volume Indicators ===")
for key, ind in self.VOLUME.items():
print(f" [{ind['name']}] {ind['signal']}")
ind = TechnicalIndicators()
ind.show_trend()
ind.show_momentum()
ind.show_volume()
Chart Patterns
# patterns.py — Chart patterns
import json
class ChartPatterns:
REVERSAL = {
"head_shoulders": {
"name": "Head and Shoulders",
"type": "Bearish Reversal",
"description": "3 peaks — กลาง (head) สูงกว่า 2 ข้าง (shoulders)",
"signal": "Break neckline → Sell | Target = Head height below neckline",
},
"double_top": {
"name": "Double Top (M)",
"type": "Bearish Reversal",
"description": "ราคาขึ้นไปแตะ resistance 2 ครั้งแล้วไม่ผ่าน",
"signal": "Break support → Sell | Target = height of pattern",
},
"double_bottom": {
"name": "Double Bottom (W)",
"type": "Bullish Reversal",
"description": "ราคาลงไปแตะ support 2 ครั้งแล้วไม่หลุด",
"signal": "Break resistance → Buy | Target = height of pattern",
},
}
CONTINUATION = {
"flag": {
"name": "Flag / Pennant",
"type": "Continuation",
"description": "หลังราคาวิ่งแรง (pole) → พักตัวเป็นรูป flag/pennant",
"signal": "Breakout ตามทิศ trend เดิม | Target = pole height",
},
"triangle": {
"name": "Triangle (Ascending, Descending, Symmetrical)",
"type": "Continuation / Neutral",
"description": "ราคาแคบลงเรื่อยๆ (converging trendlines)",
"signal": "Breakout direction = trade direction | Volume confirm",
},
}
CANDLESTICK = {
"doji": {"name": "Doji", "meaning": "ไม่แน่ใจ (indecision)", "signal": "อาจกลับตัว — ต้องดูแท่งถัดไป"},
"hammer": {"name": "Hammer / Inverted Hammer", "meaning": "Bullish reversal ที่ bottom", "signal": "Buy signal (ต้อง confirm)"},
"engulfing": {"name": "Bullish/Bearish Engulfing", "meaning": "แท่งใหม่กลืนแท่งเก่า", "signal": "Strong reversal signal"},
"morning_star": {"name": "Morning Star / Evening Star", "meaning": "3-candle reversal pattern", "signal": "Strong reversal (reliable)"},
}
def show_reversal(self):
print("=== Reversal Patterns ===\n")
for key, p in self.REVERSAL.items():
print(f"[{p['name']}] ({p['type']})")
print(f" {p['description']}")
print(f" Signal: {p['signal']}")
print()
def show_candlestick(self):
print("=== Candlestick Patterns ===")
for key, c in self.CANDLESTICK.items():
print(f" [{c['name']}] {c['meaning']} → {c['signal']}")
patterns = ChartPatterns()
patterns.show_reversal()
patterns.show_candlestick()
Python Technical Analysis
# python_ta.py — Python technical analysis
import json
class PythonTA:
CODE = """
# stock_analysis.py — Technical analysis with Python
import pandas as pd
import numpy as np
# Using ta-lib or pandas_ta
# pip install pandas_ta yfinance
import yfinance as yf
import pandas_ta as ta
# Download stock data
ticker = "PTT.BK" # PTT (SET Thailand)
df = yf.download(ticker, start="2024-01-01", end="2025-01-01")
# Calculate indicators
df['SMA_20'] = ta.sma(df['Close'], length=20)
df['SMA_50'] = ta.sma(df['Close'], length=50)
df['EMA_20'] = ta.ema(df['Close'], length=20)
df['RSI'] = ta.rsi(df['Close'], length=14)
# MACD
macd = ta.macd(df['Close'])
df = pd.concat([df, macd], axis=1)
# Bollinger Bands
bb = ta.bbands(df['Close'], length=20, std=2)
df = pd.concat([df, bb], axis=1)
# ATR
df['ATR'] = ta.atr(df['High'], df['Low'], df['Close'], length=14)
# Simple Signal Generator
def generate_signals(df):
signals = []
for i in range(len(df)):
signal = "HOLD"
# RSI signals
if df['RSI'].iloc[i] < 30:
signal = "BUY (RSI Oversold)"
elif df['RSI'].iloc[i] > 70:
signal = "SELL (RSI Overbought)"
# MA crossover
if df['SMA_20'].iloc[i] > df['SMA_50'].iloc[i] and \\
df['SMA_20'].iloc[i-1] <= df['SMA_50'].iloc[i-1]:
signal = "BUY (Golden Cross)"
elif df['SMA_20'].iloc[i] < df['SMA_50'].iloc[i] and \\
df['SMA_20'].iloc[i-1] >= df['SMA_50'].iloc[i-1]:
signal = "SELL (Death Cross)"
signals.append(signal)
df['Signal'] = signals
return df
df = generate_signals(df)
print(df[['Close', 'RSI', 'SMA_20', 'SMA_50', 'Signal']].tail(10))
"""
def show_code(self):
print("=== Python TA Code ===")
print(self.CODE[:600])
def tools_list(self):
print(f"\n=== Python TA Libraries ===")
libs = [
{"name": "pandas_ta", "description": "130+ indicators, pandas-native", "install": "pip install pandas_ta"},
{"name": "ta-lib", "description": "C library wrapper, fast, 200+ indicators", "install": "pip install TA-Lib"},
{"name": "yfinance", "description": "Download stock data from Yahoo Finance", "install": "pip install yfinance"},
{"name": "mplfinance", "description": "Candlestick charts with matplotlib", "install": "pip install mplfinance"},
{"name": "backtrader", "description": "Backtesting framework", "install": "pip install backtrader"},
]
for lib in libs:
print(f" [{lib['name']}] {lib['description']}")
pta = PythonTA()
pta.show_code()
pta.tools_list()
Trading Strategy & Risk Management
# strategy.py — Trading strategy and risk management
import json
import random
class TradingStrategy:
RISK_MANAGEMENT = {
"position_sizing": {
"name": "Position Sizing (1-2% Rule)",
"rule": "Risk ไม่เกิน 1-2% ของ portfolio ต่อ trade",
"example": "Portfolio 100,000 บาท → Risk ≤ 2,000 บาท/trade",
},
"stop_loss": {
"name": "Stop Loss",
"methods": ["Fixed % (e.g., -3%)", "ATR-based (2× ATR)", "Support level", "Trailing stop"],
"rule": "ตั้ง Stop Loss ทุกครั้ง ก่อนเปิด position",
},
"risk_reward": {
"name": "Risk-Reward Ratio",
"rule": "Minimum 1:2 (risk 1 เพื่อ reward 2)",
"example": "Stop Loss -500 บาท → Take Profit +1,000 บาท",
},
}
def show_risk(self):
print("=== Risk Management ===\n")
for key, rm in self.RISK_MANAGEMENT.items():
print(f"[{rm['name']}]")
print(f" Rule: {rm['rule']}")
print()
def position_calculator(self):
print("=== Position Size Calculator ===")
portfolio = 500000
risk_pct = 0.02
entry = 35.50
stop_loss = 33.50
risk_per_share = entry - stop_loss
max_risk = portfolio * risk_pct
shares = int(max_risk / risk_per_share)
position_value = shares * entry
print(f" Portfolio: {portfolio:,.0f} บาท")
print(f" Risk: {risk_pct*100:.0f}% = {max_risk:,.0f} บาท")
print(f" Entry: {entry} | Stop Loss: {stop_loss}")
print(f" Risk/share: {risk_per_share} บาท")
print(f" Position size: {shares:,} shares ({position_value:,.0f} บาท)")
def backtest_summary(self):
print(f"\n=== Backtest Summary (EMA Crossover) ===")
metrics = {
"Total trades": random.randint(50, 150),
"Win rate": f"{random.randint(45, 65)}%",
"Avg win": f"+{random.uniform(3, 8):.1f}%",
"Avg loss": f"-{random.uniform(1.5, 4):.1f}%",
"Max drawdown": f"-{random.uniform(10, 25):.1f}%",
"Sharpe ratio": f"{random.uniform(0.8, 2.0):.2f}",
"Total return": f"+{random.randint(15, 60)}%",
}
for m, v in metrics.items():
print(f" {m}: {v}")
strat = TradingStrategy()
strat.show_risk()
strat.position_calculator()
strat.backtest_summary()
FAQ - คำถามที่พบบ่อย
Q: Technical Analysis เชื่อถือได้ไหม?
A: TA เป็นเครื่องมือ ไม่ใช่คำตอบ 100% — ไม่มีวิธีไหนถูกต้องทุกครั้ง TA ช่วย: ระบุ trend, จุดเข้า-ออก, risk management TA ไม่ช่วย: คาดการณ์ Black Swan events, ข่าวเฉพาะบริษัท ใช้ TA + FA (Fundamental) ร่วมกัน = ดีที่สุด สำคัญที่สุด: Risk management ไม่ใช่ accuracy ของ signal
Q: มือใหม่เริ่มเรียน TA จากอะไร?
A: 1. เรียน candlestick chart อ่านแท่งเทียน 2. เรียน support/resistance 3. เรียน Moving Average (SMA, EMA) 4. เรียน RSI + MACD 5. ฝึกบน demo account 3+ เดือน หนังสือแนะนำ: Technical Analysis of the Financial Markets (John Murphy)
Q: Indicator ไหนดีที่สุด?
A: ไม่มี indicator ที่ดีที่สุด — ขึ้นอยู่กับ trading style Trend: EMA 20/50, MACD Momentum: RSI 14, Stochastic Volatility: Bollinger Bands, ATR Volume: OBV, VWAP ใช้ 2-3 indicators ร่วมกัน (ไม่ใช่ 10+) ดูว่า confirm กันหรือไม่
Q: TA ใช้ได้กับหุ้นไทย (SET) ไหม?
A: ใช้ได้ แต่มีข้อควรระวัง SET มี liquidity ต่ำกว่า US market บางตัว → patterns อาจไม่ reliable หุ้น big cap (PTT, ADVANC, SCB): TA ทำงานดี หุ้น small cap: ระวัง manipulation, volume ต่ำ ใช้ yfinance + .BK suffix (e.g., PTT.BK) สำหรับหุ้นไทย
อ่านเพิ่มเติม: สอนเทรด Forex | XM Signal | IT Hardware | อาชีพ IT
