Average
Average ค่าเฉลี่ย Mean Median Mode Weighted Geometric Harmonic Moving Average สถิติ การเงิน Python numpy pandas
| Type | Formula | เหมาะกับ | ข้อดี | ข้อเสีย |
|---|---|---|---|---|
| Arithmetic Mean | Σx / n | ข้อมูลทั่วไป | ง่าย เข้าใจง่าย | ได้รับผลจาก Outlier |
| Median | ค่ากลาง | ข้อมูลมี Outlier | ไม่ได้รับผลจาก Outlier | ไม่ใช้ข้อมูลทั้งหมด |
| Mode | ค่าที่พบบ่อย | Categorical Data | ใช้กับ Non-numeric | อาจมีหลายค่า |
| Geometric Mean | (Πx)^(1/n) | Growth Rate | แม่นสำหรับ Rate | ไม่ใช้กับค่าลบ |
| Weighted Avg | Σ(wi*xi)/Σwi | เกรด คะแนน | ให้ความสำคัญต่างกัน | ต้องกำหนดน้ำหนัก |
| Moving Avg | Avg of last n | Time Series | ดู Trend ชัด | ล่าช้า (Lag) |
Calculation Code
# === Average Calculations in Python ===
import numpy as np
from dataclasses import dataclass
# Sample Data
data = [85, 90, 78, 92, 88, 76, 95, 82, 91, 87]
# Arithmetic Mean
mean = np.mean(data)
print(f"Arithmetic Mean: {mean:.2f}")
# Median
median = np.median(data)
print(f"Median: {median:.2f}")
# Mode (using collections)
from collections import Counter
mode_count = Counter(data)
mode_val = mode_count.most_common(1)[0]
print(f"Mode: {mode_val[0]} (count: {mode_val[1]})")
# Geometric Mean
geo_mean = np.exp(np.mean(np.log(data)))
print(f"Geometric Mean: {geo_mean:.2f}")
# Harmonic Mean
harmonic = len(data) / np.sum(1.0 / np.array(data))
print(f"Harmonic Mean: {harmonic:.2f}")
# Weighted Average (GPA example)
grades = [4.0, 3.5, 3.0, 4.0, 3.5]
credits = [3, 3, 4, 2, 3]
weighted_avg = np.average(grades, weights=credits)
print(f"Weighted GPA: {weighted_avg:.2f}")
# Moving Average
prices = [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
window = 3
ma = [np.mean(prices[i:i+window]) for i in range(len(prices)-window+1)]
print(f"\nMoving Average (window={window}):")
for i, v in enumerate(ma):
print(f" Period {i+window}: {v:.2f}")
@dataclass
class AverageResult:
method: str
value: float
use_case: str
results = [
AverageResult("Arithmetic Mean", mean, "คะแนนสอบเฉลี่ย"),
AverageResult("Median", median, "รายได้เฉลี่ย (มี Outlier)"),
AverageResult("Geometric Mean", geo_mean, "ผลตอบแทนลงทุนเฉลี่ย"),
AverageResult("Harmonic Mean", harmonic, "ความเร็วเฉลี่ย"),
AverageResult("Weighted Avg", weighted_avg, "เกรดเฉลี่ย GPA"),
]
print(f"\n=== Summary ===")
for r in results:
print(f" [{r.method}] = {r.value:.2f} | Use: {r.use_case}")
Financial Applications
# === Average in Finance ===
# Moving Average for Trading
# SMA (Simple Moving Average)
def sma(prices, period):
return [np.mean(prices[i-period+1:i+1]) if i >= period-1 else None
for i in range(len(prices))]
# EMA (Exponential Moving Average)
def ema(prices, period):
result = [prices[0]]
mult = 2 / (period + 1)
for i in range(1, len(prices)):
result.append((prices[i] - result[-1]) * mult + result[-1])
return result
# VWAP (Volume Weighted Average Price)
def vwap(prices, volumes):
cum_pv = np.cumsum(np.array(prices) * np.array(volumes))
cum_vol = np.cumsum(volumes)
return cum_pv / cum_vol
# DCA (Dollar Cost Averaging)
def dca_simulation(monthly_invest, prices):
total_shares = 0
total_invested = 0
for price in prices:
shares = monthly_invest / price
total_shares += shares
total_invested += monthly_invest
avg_cost = total_invested / total_shares
current_value = total_shares * prices[-1]
profit = current_value - total_invested
return avg_cost, total_shares, current_value, profit
# DCA Example
monthly_prices = [100, 95, 90, 85, 92, 98, 105, 110, 108, 115, 120, 118]
avg_cost, shares, value, profit = dca_simulation(10000, monthly_prices)
print("=== DCA Simulation (10,000/month) ===")
print(f" Months: {len(monthly_prices)}")
print(f" Total Invested: {10000 * len(monthly_prices):,.0f}")
print(f" Average Cost: {avg_cost:.2f}")
print(f" Total Shares: {shares:.2f}")
print(f" Current Value: {value:,.0f}")
print(f" Profit/Loss: {profit:,.0f}")
print(f" Return: {profit/(10000*len(monthly_prices))*100:.1f}%")
@dataclass
class FinAvg:
concept: str
avg_type: str
formula: str
example: str
fin_avgs = [
FinAvg("SMA(20)", "Simple Moving Average", "Mean of last 20 closes", "Trend filter for trading"),
FinAvg("EMA(12,26)", "Exponential MA", "Weighted recent prices more", "MACD calculation"),
FinAvg("VWAP", "Volume Weighted", "Σ(P*V) / ΣV", "Institutional benchmark"),
FinAvg("DCA", "Dollar Cost Avg", "Fixed amount / price each period", "Long-term investing"),
FinAvg("Average Down", "Weighted Avg Cost", "(old_cost*old_qty + new_cost*new_qty) / total_qty", "Reduce cost basis"),
FinAvg("Geometric Return", "Geometric Mean", "((1+r1)*(1+r2)*...)^(1/n) - 1", "True average return"),
]
print(f"\nFinancial Averages:")
for f in fin_avgs:
print(f" [{f.concept}] Type: {f.avg_type}")
print(f" Formula: {f.formula}")
print(f" Use: {f.example}")
Statistics Applications
# === Average in Statistics ===
@dataclass
class StatExample:
scenario: str
best_average: str
reason: str
wrong_average: str
examples = [
StatExample("คะแนนสอบนักเรียน 30 คน", "Arithmetic Mean",
"ข้อมูลกระจายปกติ ไม่มี Outlier มาก", "Geometric Mean ไม่เหมาะ"),
StatExample("รายได้ประชากรในประเทศ", "Median",
"มี Outlier (มหาเศรษฐี) Mean จะสูงเกินจริง", "Mean ถูก Outlier ดึง"),
StatExample("ผลตอบแทนกองทุน 10 ปี", "Geometric Mean",
"ผลตอบแทนเป็น Compound ต้องใช้ Geometric", "Arithmetic Mean สูงเกินจริง"),
StatExample("ความเร็วเฉลี่ยไปกลับ", "Harmonic Mean",
"อัตราส่วนของระยะทาง/เวลา", "Arithmetic Mean ไม่ถูก"),
StatExample("เกรดเฉลี่ยสะสม", "Weighted Average",
"แต่ละวิชามีหน่วยกิตต่างกัน", "Simple Mean ไม่คิดน้ำหนัก"),
StatExample("ยอดขายรายเดือน ดู Trend", "Moving Average",
"ลด Noise ดู Trend ชัดขึ้น", "Single Mean ไม่เห็น Trend"),
]
print("When to Use Which Average:")
for e in examples:
print(f" [{e.scenario}]")
print(f" Best: {e.best_average} — {e.reason}")
print(f" Avoid: {e.wrong_average}")
# Common Mistakes
mistakes = {
"ใช้ Mean กับข้อมูลมี Outlier": "ใช้ Median แทน เช่น รายได้ ราคาบ้าน",
"ใช้ Arithmetic Mean กับ Return": "ใช้ Geometric Mean สำหรับ Compound Return",
"เฉลี่ย % โดยตรง": "ต้องคิดจากฐานเดียวกัน ใช้ Weighted Average",
"เปรียบเทียบ Average ไม่ดู Distribution": "ดู Standard Deviation Histogram ด้วย",
"ใช้ Average เพียงค่าเดียว": "รายงาน Mean + Median + StdDev ครบถ้วน",
}
print(f"\n\nCommon Mistakes:")
for k, v in mistakes.items():
print(f" [Mistake]: {k}")
print(f" [Fix]: {v}")
เคล็ดลับ
- Outlier: ถ้ามี Outlier ใช้ Median แทน Mean
- Return: ผลตอบแทนลงทุนใช้ Geometric Mean เสมอ
- Weight: ถ้าข้อมูลมีน้ำหนักต่างกัน ใช้ Weighted Average
- Trend: ใช้ Moving Average ดู Trend ของ Time Series
- Report: รายงาน Mean + Median + StdDev ให้ครบ
การนำความรู้ไปประยุกต์ใช้งานจริง
แหล่งเรียนรู้ที่แนะนำ ได้แก่ Official Documentation ที่อัพเดทล่าสุดเสมอ Online Course จาก Coursera Udemy edX ช่อง YouTube คุณภาพทั้งไทยและอังกฤษ และ Community อย่าง Discord Reddit Stack Overflow ที่ช่วยแลกเปลี่ยนประสบการณ์กับนักพัฒนาทั่วโลก
Average แปลว่าอะไร
ค่าเฉลี่ย ตัวแทนกลุ่มข้อมูล Arithmetic Mean Median Mode Weighted Geometric Moving Average สถิติ การเงิน วิทยาศาสตร์ ชีวิตประจำวัน
ประเภทของ Average มีอะไรบ้าง
Arithmetic Mean บวกหาร Median กลาง Outlier Mode บ่อยสุด Geometric Growth Harmonic อัตราส่วน Weighted น้ำหนัก Moving Time Series
ใช้ Average ในการเงินอย่างไร
Moving Average Trend SMA EMA VWAP Volume DCA ลงทุนเฉลี่ย Geometric Return ผลตอบแทน Average Down ลดต้นทุน
คำนวณ Average อย่างไร
Mean ผลรวมหารจำนวน Median เรียงหากลาง Mode นับบ่อยสุด Geometric ยกกำลัง 1/n Weighted น้ำหนักคูณ Python numpy pandas
สรุป
Average ค่าเฉลี่ย Mean Median Mode Geometric Harmonic Weighted Moving Average สถิติ การเงิน DCA VWAP SMA EMA Python numpy
