SiamCafe.net Blog
Technology

Technical Analysis of Financial Markets วิเคราะห์ทางเทคนคสำหรับตลาดการเงน

technical analysis of financial markets
technical analysis of financial markets | SiamCafe Blog
2025-11-01· อ. บอม — SiamCafe.net· 1,421 คำ

Technical Analysis ?????????????????????

Technical Analysis (TA) ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????? ???????????? forex cryptocurrency commodities

??????????????????????????????????????????????????? Technical Analysis ?????? 3 ????????? ?????????????????????????????????????????????????????? (Price discounts everything) ??????????????????????????????????????? ??????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????, ??????????????????????????????????????????????????????????????????????????? (Price moves in trends) ??????????????????????????? trend ??????????????????????????????????????????????????????????????????????????????????????????????????????, ????????????????????????????????????????????????????????? (History repeats itself) ????????????????????????????????????????????????????????????????????????????????????????????????

??????????????????????????????????????????????????? TA ?????????????????? Chart Patterns (Head & Shoulders, Double Top/Bottom, Triangles), Indicators (Moving Average, RSI, MACD, Bollinger Bands), Volume Analysis (??????????????????????????????????????????????????????????????????????????????), Support/Resistance (?????????????????? ?????????????????????), Candlestick Patterns (Doji, Hammer, Engulfing)

?????????????????????????????????????????????????????????????????????????????????????????????????????????

Indicators ????????????????????????????????????????????????

# === Technical Analysis Indicators ===

cat > indicators.yaml << 'EOF'
technical_indicators:
  trend_indicators:
    moving_average:
      sma:
        name: "Simple Moving Average"
        formula: "Average of last N closing prices"
        common_periods: [20, 50, 100, 200]
        signal: "Price above SMA = uptrend, below = downtrend"
        golden_cross: "SMA50 crosses above SMA200 = bullish"
        death_cross: "SMA50 crosses below SMA200 = bearish"
      ema:
        name: "Exponential Moving Average"
        formula: "Weighted average, recent prices get more weight"
        common_periods: [9, 12, 26, 50]
        advantage: "Responds faster to price changes than SMA"
        
    macd:
      name: "Moving Average Convergence Divergence"
      components:
        macd_line: "EMA(12) - EMA(26)"
        signal_line: "EMA(9) of MACD line"
        histogram: "MACD line - Signal line"
      signals:
        bullish: "MACD crosses above signal line"
        bearish: "MACD crosses below signal line"
        divergence: "Price makes new high but MACD doesn't = weakness"

  momentum_indicators:
    rsi:
      name: "Relative Strength Index"
      range: "0-100"
      overbought: "> 70 (????????????????????????????????????)"
      oversold: "< 30 (??????????????????????????????????????????)"
      period: 14
      divergence: "RSI divergence ????????????????????????????????????????????????"
      
    stochastic:
      name: "Stochastic Oscillator"
      range: "0-100"
      overbought: "> 80"
      oversold: "< 20"
      components: ["%K line (fast)", "%D line (slow)"]
      
  volatility_indicators:
    bollinger_bands:
      name: "Bollinger Bands"
      components:
        middle: "SMA(20)"
        upper: "SMA(20) + 2*StdDev"
        lower: "SMA(20) - 2*StdDev"
      signal: "Price touching upper band = overbought, lower = oversold"
      squeeze: "Bands narrow = low volatility, breakout coming"
      
    atr:
      name: "Average True Range"
      use: "Measure volatility, set stop-loss distance"
      period: 14

  volume_indicators:
    obv:
      name: "On-Balance Volume"
      use: "Confirm trend with volume"
    vwap:
      name: "Volume Weighted Average Price"
      use: "Institutional benchmark price"
EOF

echo "Indicators guide defined"

?????????????????????????????????????????????????????????????????? Python

Technical analysis library ???????????? Python

#!/usr/bin/env python3
# ta_system.py ??? Technical Analysis System
import json
import logging
import math
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("ta")

class TechnicalAnalysis:
    def __init__(self):
        self.data = []
    
    def sma(self, prices, period):
        """Simple Moving Average"""
        if len(prices) < period:
            return []
        result = []
        for i in range(period - 1, len(prices)):
            avg = sum(prices[i - period + 1:i + 1]) / period
            result.append(round(avg, 2))
        return result
    
    def ema(self, prices, period):
        """Exponential Moving Average"""
        if len(prices) < period:
            return []
        multiplier = 2 / (period + 1)
        ema_values = [sum(prices[:period]) / period]
        for price in prices[period:]:
            ema_values.append(round((price - ema_values[-1]) * multiplier + ema_values[-1], 2))
        return ema_values
    
    def rsi(self, prices, period=14):
        """Relative Strength Index"""
        if len(prices) < period + 1:
            return []
        
        changes = [prices[i] - prices[i-1] for i in range(1, len(prices))]
        gains = [max(c, 0) for c in changes]
        losses = [abs(min(c, 0)) for c in changes]
        
        avg_gain = sum(gains[:period]) / period
        avg_loss = sum(losses[:period]) / period
        
        rsi_values = []
        for i in range(period, len(changes)):
            avg_gain = (avg_gain * (period - 1) + gains[i]) / period
            avg_loss = (avg_loss * (period - 1) + losses[i]) / period
            
            if avg_loss == 0:
                rsi_values.append(100)
            else:
                rs = avg_gain / avg_loss
                rsi_values.append(round(100 - (100 / (1 + rs)), 2))
        
        return rsi_values
    
    def bollinger_bands(self, prices, period=20, std_dev=2):
        """Bollinger Bands"""
        if len(prices) < period:
            return {"upper": [], "middle": [], "lower": []}
        
        middle = self.sma(prices, period)
        upper = []
        lower = []
        
        for i in range(len(middle)):
            idx = i + period - 1
            window = prices[idx - period + 1:idx + 1]
            mean = sum(window) / period
            variance = sum((x - mean) ** 2 for x in window) / period
            std = math.sqrt(variance)
            upper.append(round(middle[i] + std_dev * std, 2))
            lower.append(round(middle[i] - std_dev * std, 2))
        
        return {"upper": upper, "middle": middle, "lower": lower}
    
    def macd(self, prices, fast=12, slow=26, signal=9):
        """MACD"""
        ema_fast = self.ema(prices, fast)
        ema_slow = self.ema(prices, slow)
        
        offset = slow - fast
        macd_line = [round(ema_fast[i + offset] - ema_slow[i], 2) for i in range(len(ema_slow))]
        signal_line = self.ema(macd_line, signal)
        
        offset2 = signal - 1
        histogram = [round(macd_line[i + offset2] - signal_line[i], 2) for i in range(len(signal_line))]
        
        return {"macd": macd_line, "signal": signal_line, "histogram": histogram}
    
    def generate_signals(self, prices):
        """Generate buy/sell signals"""
        signals = []
        
        rsi_vals = self.rsi(prices)
        if rsi_vals:
            last_rsi = rsi_vals[-1]
            if last_rsi < 30:
                signals.append({"indicator": "RSI", "signal": "BUY", "value": last_rsi, "reason": "Oversold"})
            elif last_rsi > 70:
                signals.append({"indicator": "RSI", "signal": "SELL", "value": last_rsi, "reason": "Overbought"})
            else:
                signals.append({"indicator": "RSI", "signal": "NEUTRAL", "value": last_rsi})
        
        sma20 = self.sma(prices, 20)
        sma50 = self.sma(prices, 50)
        if sma20 and sma50:
            if sma20[-1] > sma50[-1]:
                signals.append({"indicator": "SMA Cross", "signal": "BUY", "reason": "SMA20 > SMA50"})
            else:
                signals.append({"indicator": "SMA Cross", "signal": "SELL", "reason": "SMA20 < SMA50"})
        
        return signals

ta = TechnicalAnalysis()

# Sample price data
prices = [100, 102, 101, 103, 105, 104, 106, 108, 107, 109,
          111, 110, 112, 114, 113, 115, 117, 116, 118, 120,
          119, 121, 123, 122, 124, 126, 125, 127, 129, 128,
          130, 129, 128, 127, 126, 125, 124, 123, 122, 121,
          120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
          130, 131, 132, 133, 134]

sma20 = ta.sma(prices, 20)
rsi = ta.rsi(prices)
bb = ta.bollinger_bands(prices)

print(f"SMA20 (last 3): {sma20[-3:]}")
print(f"RSI (last 3): {rsi[-3:]}")
print(f"BB Upper: {bb['upper'][-1]}, Middle: {bb['middle'][-1]}, Lower: {bb['lower'][-1]}")

signals = ta.generate_signals(prices)
for s in signals:
    print(f"  {s['indicator']}: {s['signal']} ??? {s.get('reason', '')}")

Indicators ?????????????????????

Advanced technical indicators

#!/usr/bin/env python3
# advanced_ta.py ??? Advanced Technical Analysis
import json
import logging
import math
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("advanced_ta")

class AdvancedTA:
    def __init__(self):
        pass
    
    def fibonacci_retracement(self, high, low):
        """Calculate Fibonacci retracement levels"""
        diff = high - low
        levels = {
            "0.0%": high,
            "23.6%": round(high - diff * 0.236, 2),
            "38.2%": round(high - diff * 0.382, 2),
            "50.0%": round(high - diff * 0.500, 2),
            "61.8%": round(high - diff * 0.618, 2),
            "78.6%": round(high - diff * 0.786, 2),
            "100.0%": low,
        }
        return {"high": high, "low": low, "levels": levels}
    
    def pivot_points(self, high, low, close):
        """Calculate pivot points"""
        pivot = round((high + low + close) / 3, 2)
        return {
            "R3": round(high + 2 * (pivot - low), 2),
            "R2": round(pivot + (high - low), 2),
            "R1": round(2 * pivot - low, 2),
            "Pivot": pivot,
            "S1": round(2 * pivot - high, 2),
            "S2": round(pivot - (high - low), 2),
            "S3": round(low - 2 * (high - pivot), 2),
        }
    
    def ichimoku_cloud(self):
        """Ichimoku Cloud components"""
        return {
            "components": {
                "tenkan_sen": {"period": 9, "calc": "(highest high + lowest low) / 2", "name": "Conversion Line"},
                "kijun_sen": {"period": 26, "calc": "(highest high + lowest low) / 2", "name": "Base Line"},
                "senkou_span_a": {"calc": "(Tenkan + Kijun) / 2, plotted 26 periods ahead", "name": "Leading Span A"},
                "senkou_span_b": {"period": 52, "calc": "(highest high + lowest low) / 2, plotted 26 periods ahead", "name": "Leading Span B"},
                "chikou_span": {"calc": "Close plotted 26 periods back", "name": "Lagging Span"},
            },
            "signals": {
                "strong_buy": "Price above cloud + Tenkan above Kijun + Chikou above price",
                "buy": "Price crosses above cloud",
                "sell": "Price crosses below cloud",
                "strong_sell": "Price below cloud + Tenkan below Kijun + Chikou below price",
            },
            "cloud_color": {
                "green": "Senkou A above Senkou B (bullish)",
                "red": "Senkou B above Senkou A (bearish)",
            },
        }
    
    def market_summary(self, price, indicators):
        """Aggregate multiple indicators into summary"""
        buy_signals = sum(1 for i in indicators if i["signal"] == "BUY")
        sell_signals = sum(1 for i in indicators if i["signal"] == "SELL")
        neutral = sum(1 for i in indicators if i["signal"] == "NEUTRAL")
        total = len(indicators)
        
        if buy_signals > sell_signals * 2:
            recommendation = "STRONG BUY"
        elif buy_signals > sell_signals:
            recommendation = "BUY"
        elif sell_signals > buy_signals * 2:
            recommendation = "STRONG SELL"
        elif sell_signals > buy_signals:
            recommendation = "SELL"
        else:
            recommendation = "NEUTRAL"
        
        return {
            "price": price,
            "buy_signals": buy_signals,
            "sell_signals": sell_signals,
            "neutral": neutral,
            "recommendation": recommendation,
            "confidence": round(max(buy_signals, sell_signals) / max(total, 1) * 100, 1),
        }

ta = AdvancedTA()

fib = ta.fibonacci_retracement(high=150, low=100)
print("Fibonacci Retracement:")
for level, price in fib["levels"].items():
    print(f"  {level}: {price}")

pivots = ta.pivot_points(high=150, low=140, close=145)
print("\nPivot Points:")
for level, price in pivots.items():
    print(f"  {level}: {price}")

indicators = [
    {"indicator": "RSI", "signal": "BUY"},
    {"indicator": "MACD", "signal": "BUY"},
    {"indicator": "SMA", "signal": "SELL"},
    {"indicator": "BB", "signal": "NEUTRAL"},
    {"indicator": "Stochastic", "signal": "BUY"},
]
summary = ta.market_summary(145, indicators)
print(f"\nSummary: {summary['recommendation']} (confidence: {summary['confidence']}%)")

Backtesting ??????????????????????????????????????????

??????????????????????????????????????????????????????????????????????????????????????????

#!/usr/bin/env python3
# backtest.py ??? Strategy Backtesting
import json
import logging
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("backtest")

class Backtester:
    def __init__(self, initial_capital=100000):
        self.initial_capital = initial_capital
        self.trades = []
    
    def sma_crossover_strategy(self, prices, fast_period=20, slow_period=50):
        """SMA Crossover strategy backtest"""
        if len(prices) < slow_period:
            return {"error": "Not enough data"}
        
        capital = self.initial_capital
        position = 0
        entry_price = 0
        trades = []
        
        for i in range(slow_period, len(prices)):
            fast_sma = sum(prices[i - fast_period:i]) / fast_period
            slow_sma = sum(prices[i - slow_period:i]) / slow_period
            prev_fast = sum(prices[i - fast_period - 1:i - 1]) / fast_period
            prev_slow = sum(prices[i - slow_period - 1:i - 1]) / slow_period
            
            # Golden cross (buy)
            if prev_fast <= prev_slow and fast_sma > slow_sma and position == 0:
                shares = int(capital / prices[i])
                if shares > 0:
                    position = shares
                    entry_price = prices[i]
                    capital -= shares * prices[i]
                    trades.append({"type": "BUY", "price": prices[i], "shares": shares, "day": i})
            
            # Death cross (sell)
            elif prev_fast >= prev_slow and fast_sma < slow_sma and position > 0:
                capital += position * prices[i]
                pnl = (prices[i] - entry_price) * position
                trades.append({"type": "SELL", "price": prices[i], "shares": position, "pnl": round(pnl, 2), "day": i})
                position = 0
        
        # Close open position
        if position > 0:
            capital += position * prices[-1]
        
        total_return = (capital - self.initial_capital) / self.initial_capital * 100
        winning = [t for t in trades if t.get("pnl", 0) > 0]
        losing = [t for t in trades if t.get("pnl", 0) < 0]
        
        return {
            "strategy": f"SMA {fast_period}/{slow_period} Crossover",
            "initial_capital": self.initial_capital,
            "final_capital": round(capital, 2),
            "total_return_pct": round(total_return, 2),
            "total_trades": len([t for t in trades if t["type"] == "SELL"]),
            "winning_trades": len(winning),
            "losing_trades": len(losing),
            "win_rate": round(len(winning) / max(len(winning) + len(losing), 1) * 100, 1),
            "buy_hold_return": round((prices[-1] - prices[0]) / prices[0] * 100, 2),
        }

bt = Backtester(100000)

# Generate sample trending market data
import random
random.seed(42)
prices = [100]
for i in range(250):
    change = random.gauss(0.1, 2)
    prices.append(round(max(prices[-1] + change, 50), 2))

result = bt.sma_crossover_strategy(prices)
print(f"Strategy: {result['strategy']}")
print(f"Return: {result['total_return_pct']}%")
print(f"Buy & Hold: {result['buy_hold_return']}%")
print(f"Trades: {result['total_trades']}, Win rate: {result['win_rate']}%")
print(f"Final Capital: {result['final_capital']:,.0f} THB")

??????????????? Dashboard ??????????????????????????????

????????????????????????????????????????????????????????????

# === Market Dashboard Setup ===

# 1. Install Python TA Libraries
pip install yfinance ta pandas matplotlib plotly

# 2. Quick Analysis Script
cat > market_dashboard.py << 'PYEOF'
#!/usr/bin/env python3
"""Market analysis dashboard"""
import json

class MarketDashboard:
    def __init__(self):
        self.watchlist = []
    
    def add_to_watchlist(self, symbol, name):
        self.watchlist.append({"symbol": symbol, "name": name})
    
    def recommended_tools(self):
        return {
            "charting": {
                "tradingview": "Best free charting, 100+ indicators",
                "plotly": "Python interactive charts",
                "matplotlib": "Python static charts",
            },
            "data_sources": {
                "yfinance": "Free Yahoo Finance API (pip install yfinance)",
                "alpha_vantage": "Free API, 5 req/min",
                "polygon": "Free tier, real-time US stocks",
                "bitkub_api": "Thai crypto exchange API",
            },
            "ta_libraries": {
                "ta": "pip install ta ??? 100+ indicators",
                "ta_lib": "pip install TA-Lib ??? C-based, fastest",
                "pandas_ta": "pip install pandas_ta ??? pandas integration",
            },
            "backtesting": {
                "backtrader": "pip install backtrader ??? comprehensive",
                "bt": "pip install bt ??? simple and clean",
                "zipline": "Quantopian's backtesting engine",
            },
        }

dash = MarketDashboard()
tools = dash.recommended_tools()
print("Recommended Tools:")
for category, items in tools.items():
    print(f"\n  {category}:")
    for name, desc in items.items():
        print(f"    {name}: {desc}")
PYEOF

python3 market_dashboard.py

echo "Dashboard configured"

FAQ ??????????????????????????????????????????

Q: Technical Analysis ????????????????????????????????????????

A: TA ????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????? 100% ??????????????? ????????????????????????????????????????????????-????????? (entry/exit), ????????? framework ??????????????????????????????????????? ?????? emotional trading, ???????????????????????????????????????????????? ????????? timeframe, ?????????????????????????????? stop-loss ???????????????????????????????????? ???????????????????????? ??????????????? indicator ??????????????? 100% (60-70% win rate ????????????????????????), ????????????????????????????????????????????????????????????????????????????????? override TA ?????????, Past performance ????????? guarantee future results, ?????????????????????????????????????????? risk management TA ??????????????????????????????????????????????????????????????? money management ??????????????? ??????????????????????????? indicator ????????????????????????????????????????????????

Q: Indicator ???????????????????????????????????????????

A: ??????????????? indicator ??????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????? 2-3 ????????? Trending market ????????? Moving Average (SMA/EMA), MACD ????????????????????????, Ranging market ????????? RSI, Stochastic, Bollinger Bands ??????????????????, Volatile market ????????? ATR ??????????????? stop-loss, Bollinger Bands ????????? volatility ??????????????????????????????????????? ??????????????????????????????????????? SMA 20/50 + RSI 14 + Volume ?????????????????? 3 ????????????????????????????????????????????????????????????????????? ????????????????????? indicators ??????????????????????????? (indicator overload) ??????????????? confuse

Q: Timeframe ????????????????????????????????? style ????????????????????????????????????????

A: ????????????????????? trading style Scalping ????????? 1-5 ???????????? ???????????????????????????????????????????????? ?????????????????????????????????????????? ??????????????????????????????????????????, Day Trading ????????? 15 ????????????-1 ????????????????????? ???????????????????????????????????? ?????????????????? position ?????????????????????????????????, Swing Trading ????????? 4 ?????????????????????-Daily ????????? 2-10 ????????? ??????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????, Position Trading ????????? Daily-Weekly ????????? weeks-months ??????????????????????????????????????? ??????????????? ??????????????????????????????????????????????????????????????? Daily chart + Swing trading ?????????????????????????????? ???????????????????????????????????????????????????????????? ?????????????????????????????????????????????

Q: Backtesting ??????????????????????????????????

A: ???????????????????????? ?????????????????????????????????????????? backtest ????????????????????????????????????????????? ?????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????, ????????? drawdown ?????????????????? (????????????????????????????????????????????????????????????????????????????????????????????????), ???????????? parameters ?????????????????????????????? (optimize), ?????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????? Overfitting ???????????? optimize ??????????????????????????? (curve fitting), ????????? out-of-sample data ??????????????? (train/test split), Slippage ????????????????????????????????????????????? ?????????????????????????????????, Past performance ??? future results ???????????? Python libraries ???????????????????????? backtrader, bt, zipline

📖 บทความที่เกี่ยวข้อง

gold technical analysis support resistance xauusdอ่านบทความ → financial markets technical analysisอ่านบทความ → technical analysis the financial marketsอ่านบทความ → technical analysis of the financial marketsอ่านบทความ → technical analysis of the financial marketอ่านบทความ →

📚 ดูบทความทั้งหมด →