GaiaEx AcademyGaiaEx Academy
Pandas, NumPy, Matplotlib ഉപയോഗിച്ചുള്ള ഡേറ്റ അനാലിസിസ്
ഡെവലപ്പർപ്രോഗ്രാമിംഗ്12 min read

Pandas, NumPy, Matplotlib ഉപയോഗിച്ചുള്ള ഡേറ്റ അനാലിസിസ്

ഒരു ക്വാണ്ടിനെപ്പോലെ ധനകാര്യ ഡേറ്റ ശുദ്ധീകരിക്കുക, രൂപാന്തരപ്പെടുത്തുക, ദൃശ്യവൽക്കരിക്കുക

പോസ്റ്റുകൾ പങ്കിടുക

NumPy: അകത്തുള്ള എൻജിൻ

Python-ൽ എഴുതുന്ന ഏതൊരു ഗൗരവമായ ധനകാര്യ കണക്കുകൂട്ടലും അവസാനം NumPy-യിലൂടെയാണ് പ്രവർത്തിക്കുന്നത്. Python list-കൾ flexible ആണെങ്കിലും വേഗത കുറവാണ്—ഓരോ element-ഉം type checking overhead ഉള്ള ഒരു full Python object ആണ്. NumPy array-കൾ അസംസ്കൃത സംഖ്യകൾ contiguous memory block-കളിൽ സൂക്ഷിക്കുന്നു, ഇത് pure Python loop-കളേക്കാൾ 100 മടങ്ങ് വേഗത്തിൽ പ്രവർത്തിക്കുന്ന operation-കൾ സാധ്യമാക്കുന്നു.

പ്രായോഗികമായി ഈ വ്യത്യാസം ഇങ്ങനെയാണ്:

import numpy as np

# Create an array of 1 million random daily returns
returns = np.random.normal(0.0005, 0.02, 1_000_000)

# Vectorized operations — no loops needed
cumulative = np.cumprod(1 + returns)  # Growth of $1
sharpe = returns.mean() / returns.std() * np.sqrt(252)
max_drawdown = np.min(cumulative / np.maximum.accumulate(cumulative) - 1)

print(f"Sharpe Ratio: {sharpe:.3f}")
print(f"Max Drawdown: {max_drawdown:.2%}")

ധനകാര്യത്തിന് പ്രധാനമായ NumPy concept-കൾ:

  • Vectorized operations — element by element loop ചെയ്യുന്നതിന് പകരം മുഴുവൻ array-കൾക്കും ഒറ്റയടിക്ക് math apply ചെയ്യുക.
  • Broadcasting — arithmetic-നായി വ്യത്യസ്ത shape-ഉള്ള array-കൾ യാന്ത്രികമായി align ചെയ്യുന്നു (ഉദാ: ഓരോ element-ൽ നിന്നും ഒരു scalar mean കുറയ്ക്കുന്നത്).
  • Linear algebranp.linalg portfolio optimization-ൽ ഉപയോഗിക്കുന്ന matrix multiplication, eigenvalue decomposition, solver-കൾ നൽകുന്നു.
  • Random sampling — Monte Carlo simulation-കൾ, bootstrap sampling, stochastic modeling ഇവയെല്ലാം np.random-നെ ആശ്രയിക്കുന്നു.

Performance ടിപ്പ്: Python for-loop-കളേക്കാൾ എപ്പോഴും vectorized NumPy operation-കൾ തിരഞ്ഞെടുക്കുക. loop-കൾ ഉപയോഗിച്ചാൽ 30 സെക്കൻഡ് എടുക്കുന്ന 500 അസറ്റുകളുടെ portfolio optimization, vectorized NumPy ഉപയോഗിച്ചാൽ 50 milliseconds-ൽ താഴെ പൂർത്തിയാക്കാം — അതായത് 600 മടങ്ങ് വേഗത.

NumPy: contiguous memory + vectorized ops ndarray — dtype, shape, strides (C-contiguous) one loop in C/Fortran, not a million Python bytecode steps broadcasting: align shapes for element-wise math e.g. returns vector − scalar mean, or (n,) with (n, m) matrix rows linalg: cov, eig, solve — portfolio math lives here
Array-കൾ ആണ് വേഗതയുള്ള പാത; broadcasting ആണ് loop-കൾ ഇല്ലാതെ കോഡ് വായിക്കാൻ എളുപ്പമാക്കുന്ന മാർഗ്ഗം.

Pandas: ധനകാര്യ ഡേറ്റക്കുള്ള DataFrame-കൾ

NumPy ഒരു എൻജിൻ ആണെങ്കിൽ, pandas ആണ് dashboard. ഇത് NumPy array-കളെ labeled, indexed structure-കളിൽ പൊതിഞ്ഞ്, ധനകാര്യ ഡേറ്റ കൈകാര്യം ചെയ്യുന്നത് സ്വാഭാവികവും വ്യക്തവുമാക്കുന്നു.

രണ്ട് പ്രധാന structure-കൾ ഇവയാണ്:

  • Series — index ഉള്ള ഒരു single column ഡേറ്റ (ഉദാ: closing price-കളുടെ ഒരു time series).
  • DataFrame — column-കളുടെ ഒരു table, ഓരോന്നും ഒരു Series, എല്ലാം ഒരു common index പങ്കിടുന്നു (ഉദാ: OHLCV കാൻഡിൽസ്റ്റിക്ക് ഡേറ്റ).

ഡേറ്റ load ചെയ്ത് inspect ചെയ്യുന്നത് വളരെ ലളിതമാണ്:

import pandas as pd

# Read from CSV
df = pd.read_csv("btc_daily.csv", parse_dates=["date"], index_col="date")

# Or from JSON (common in API responses)
df = pd.read_json("https://api.example.com/candles?symbol=ETH")

# Quick inspection
print(df.shape)          # (365, 5)
print(df.dtypes)         # Column types
print(df.describe())     # Statistical summary
print(df.tail())         # Last 5 rows

ധനകാര്യത്തിന് pandas ഒഴിച്ചുകൂടാൻ പറ്റാത്തതാക്കുന്നത് അതിന്റെ DatetimeIndex ആണ്. നിങ്ങളുടെ index datetime-typed ആയാൽ, ശക്തമായ time-series operation-കൾ അൺലോക്ക് ചെയ്യപ്പെടും:

# Slice by date range
q1_data = df["2025-01":"2025-03"]

# Resample daily data to weekly OHLC
weekly = df["close"].resample("W").ohlc()

# Forward-fill missing data (weekends, holidays)
df = df.asfreq("D").ffill()

ധനകാര്യ ഡേറ്റയുടെ കുഴപ്പം പിടിച്ച യാഥാർത്ഥ്യങ്ങൾ—gap-കൾ, timezone വ്യത്യാസങ്ങൾ, ക്രമരഹിതമായ timestamp-കൾ—ഈ operation-കൾ കൈകാര്യം ചെയ്യുന്നു, അതുകൊണ്ട് ഡേറ്റ plumbing-ന് പകരം analysis-ൽ ശ്രദ്ധ കേന്ദ്രീകരിക്കാം.

Rolling കണക്കുകൂട്ടലുകൾ: Moving Average-കളും Volatility-യും

ധനകാര്യ വിശകലനം സ്വാഭാവികമായി windowed ആണ്. ഒറ്റപ്പെട്ട ഒരു ഡേറ്റ പോയിന്റിനെ കുറിച്ച് നിങ്ങൾ അപൂർവ്വമായി മാത്രമേ ശ്രദ്ധിക്കുന്നുള്ളൂ—context വരുന്നത് അത് സമീപകാല ചരിത്രവുമായി എങ്ങനെ ബന്ധപ്പെട്ടിരിക്കുന്നു എന്നതിൽ നിന്നാണ്. Pandas-ന്റെ .rolling() method ആണ് ഇവിടെ നിങ്ങളുടെ പ്രധാന tool.

import pandas as pd
import numpy as np

# Assume df has a "close" column with DatetimeIndex
df["sma_20"] = df["close"].rolling(20).mean()
df["sma_50"] = df["close"].rolling(50).mean()
df["ema_12"] = df["close"].ewm(span=12).mean()

# Daily returns and rolling volatility
df["returns"] = df["close"].pct_change()
df["vol_30d"] = df["returns"].rolling(30).std() * np.sqrt(365)

# Bollinger Bands
df["bb_upper"] = df["sma_20"] + 2 * df["close"].rolling(20).std()
df["bb_lower"] = df["sma_20"] - 2 * df["close"].rolling(20).std()

# Rolling correlation between two assets
df["corr_btc_eth"] = df["btc_returns"].rolling(60).corr(df["eth_returns"])

ഓരോ ട്രേഡറും അറിഞ്ഞിരിക്കേണ്ട പ്രധാന rolling കണക്കുകൂട്ടലുകൾ:

  • Simple Moving Average (SMA) — N periods-ൽ equal-weighted average. Lagging പക്ഷേ stable.
  • Exponential Moving Average (EMA).ewm() വഴി സമീപകാല ഡേറ്റക്ക് കൂടുതൽ weight നൽകുന്നു. വില മാറ്റങ്ങളോട് കൂടുതൽ responsive.
  • Rolling Volatility — ഒരു window-ൽ returns-ന്റെ standard deviation, annualized. Position sizing-നും risk budget-കൾക്കും അത്യാവശ്യം.
  • Rolling Correlation — രണ്ട് അസറ്റുകൾ കാലക്രമേണ ഒരുമിച്ച് എങ്ങനെ നീങ്ങുന്നു എന്ന് അളക്കുന്നു. Portfolio diversification-ന് നിർണ്ണായകം.

GaiaEx പോലുള്ള platform-കളിൽ, trading API വഴി historical candle ഡേറ്റ വലിച്ചെടുത്ത്, ഒരു pandas DataFrame-ലേക്ക് load ചെയ്ത്, സെക്കൻഡുകൾക്കുള്ളിൽ ഈ indicator-കൾ കണക്കാക്കാം—നിങ്ങളുടെ അസറ്റുകൾ നിങ്ങളുടെ MPC വാലറ്റിൽ സുരക്ഷിതമായി തുടരുമ്പോൾ തന്നെ.

Portfolio വിശകലനത്തിനുള്ള GroupBy ഉം Aggregation-ഉം

നിങ്ങൾ ഒന്നിലധികം അസറ്റുകൾ manage ചെയ്യുമ്പോൾ, .groupby() അത്യാവശ്യമായി മാറുന്നു. ഇത് category അനുസരിച്ച് ഡേറ്റ split ചെയ്യാനും, കണക്കുകൂട്ടലുകൾ apply ചെയ്യാനും, ഫലങ്ങൾ combine ചെയ്യാനും അനുവദിക്കുന്നു—split-apply-combine pattern.

# DataFrame with multiple assets
trades = pd.DataFrame({
    "symbol": ["BTC", "ETH", "BTC", "SOL", "ETH", "BTC"],
    "side": ["buy", "buy", "sell", "buy", "sell", "buy"],
    "pnl": [120.5, -45.2, 89.0, 210.3, 55.8, -30.1],
    "volume": [5000, 3200, 4800, 1500, 2900, 5100],
})

# Performance by asset
summary = trades.groupby("symbol").agg(
    total_pnl=("pnl", "sum"),
    avg_pnl=("pnl", "mean"),
    trade_count=("pnl", "count"),
    total_volume=("volume", "sum"),
    win_rate=("pnl", lambda x: (x > 0).mean()),
)

print(summary.sort_values("total_pnl", ascending=False))

Portfolio work-ന് വേണ്ട advanced aggregation pattern-കൾ:

  • Multi-level groupby — ഓരോ അസറ്റിന്റെയും long vs. short performance കാണാൻ symbol ഉം side-ഉം അനുസരിച്ച് group ചെയ്യുക.
  • Custom aggregation function-കൾ — ഓരോ asset group-ന്റെയും Sharpe ratio, Sortino ratio, max drawdown കണക്കാക്കുക.
  • Pivot table-കൾpd.pivot_table() ഉപയോഗിച്ച് heatmap-friendly format-ൽ asset അനുസരിച്ചുള്ള monthly returns കാണാൻ ഡേറ്റ reshape ചെയ്യുക.
  • Groupby-യോടൊപ്പം resampling — multi-asset time-series വിശകലനത്തിന് time-based resampling-നെ categorical grouping-മായി combine ചെയ്യുക.

Matplotlib: വില ചലനവും Signal-കളും ചാർട്ട് ചെയ്യുക

Visualization ഇല്ലാത്ത ഡേറ്റ വെറും സംഖ്യകൾ മാത്രമാണ്. Matplotlib നിങ്ങളുടെ analysis-നെ, അസംസ്കൃത ഡേറ്റയിൽ അദൃശ്യമായ pattern-കൾ വെളിപ്പെടുത്തുന്ന ചാർട്ടുകളാക്കി മാറ്റുന്നു.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, axes = plt.subplots(3, 1, figsize=(14, 10),
                         sharex=True, gridspec_kw={"height_ratios": [3, 1, 1]})

# Price + Moving Averages
axes[0].plot(df.index, df["close"], label="Close", linewidth=1.2)
axes[0].plot(df.index, df["sma_20"], label="SMA 20", linestyle="--")
axes[0].fill_between(df.index, df["bb_upper"], df["bb_lower"],
                     alpha=0.1, color="blue", label="Bollinger Bands")
axes[0].set_ylabel("Price (USD)")
axes[0].legend(loc="upper left")

# Volume bars
colors = ["green" if c > o else "red"
          for c, o in zip(df["close"], df["open"])]
axes[1].bar(df.index, df["volume"], color=colors, alpha=0.7)
axes[1].set_ylabel("Volume")

# Rolling Volatility
axes[2].plot(df.index, df["vol_30d"], color="purple")
axes[2].set_ylabel("30d Volatility")
axes[2].axhline(y=0.8, color="red", linestyle=":", alpha=0.5)

axes[2].xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
plt.tight_layout()
plt.savefig("analysis_dashboard.png", dpi=150)
plt.show()

ഇത് ഒരു professional three-panel dashboard നിർമ്മിക്കുന്നു: മുകളിൽ Bollinger Bands-ഓടെയുള്ള വില ചലനം, മധ്യത്തിൽ volume, താഴെ volatility. ഈ layout, professional trading terminal-കളിൽ കാണുന്നതിനെ പ്രതിഫലിപ്പിക്കുന്നു.

Statistical visualization-ന്, seaborn Matplotlib-ന് മുകളിൽ higher-level function-കൾ ഉപയോഗിച്ച് നിർമ്മിച്ചിരിക്കുന്നു:

import seaborn as sns

# Return distribution
sns.histplot(df["returns"].dropna(), bins=100, kde=True)

# Correlation heatmap across assets
corr_matrix = portfolio_returns.corr()
sns.heatmap(corr_matrix, annot=True, cmap="RdYlGn", center=0)
Pandas → analysis; Matplotlib → insight DataFrame index + columns rolling resample groupby Series metrics returns, vol, Sharpe matplotlib.pyplot — figure, axes, artists price volume indicators seaborn optional — same Artist layer, prettier defaults
Pandas വൃത്തിയുള്ള table-കൾ തയ്യാറാക്കുന്നു; Matplotlib അവയെ നിങ്ങൾക്ക് annotate ചെയ്ത് പങ്കുവെക്കാവുന്ന axes-ലേക്ക് map ചെയ്യുന്നു.

എല്ലാം ഒരുമിച്ച് ചേർക്കുന്നു: ഒരു Complete Analysis Pipeline

ഈ tool-കൾ ഒരു repeatable pipeline-ലേക്ക് chain ചെയ്യുമ്പോൾ ആണ് യഥാർത്ഥ ശക്തി ഉയരുന്നത്. Professional quant-കൾ ദിവസവും ഉപയോഗിക്കുന്ന ഒരു workflow ഇതാ:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def analyze_asset(symbol: str, df: pd.DataFrame) -> dict:
    """Full analysis pipeline for a single asset."""
    df["returns"] = df["close"].pct_change()
    df["log_returns"] = np.log(df["close"] / df["close"].shift(1))

    return {
        "symbol": symbol,
        "total_return": (df["close"].iloc[-1] / df["close"].iloc[0]) - 1,
        "annual_vol": df["returns"].std() * np.sqrt(365),
        "sharpe": df["returns"].mean() / df["returns"].std() * np.sqrt(365),
        "max_drawdown": (df["close"] / df["close"].cummax() - 1).min(),
        "skewness": df["returns"].skew(),
        "kurtosis": df["returns"].kurtosis(),
    }

# Analyze multiple assets
results = [analyze_asset(sym, data) for sym, data in assets.items()]
summary = pd.DataFrame(results).set_index("symbol")
print(summary.round(4))

ഈ pipeline അസംസ്കൃത price ഡേറ്റ എടുത്ത്, ഓരോ അസറ്റിനും ഒരു comprehensive risk-return profile ഉണ്ടാക്കുന്നു. ഇവിടെ നിന്ന്, ഈ metric-കൾ ഒരു portfolio optimizer-ലേക്ക് feed ചെയ്യാം, allocation നിർദ്ദേശങ്ങൾ generate ചെയ്യാം, അല്ലെങ്കിൽ rebalancing signal-കൾ trigger ചെയ്യാം.

pandas-NumPy-Matplotlib stack ആണ് Python finance-ൽ മറ്റെല്ലാം നിർമ്മിക്കപ്പെടുന്ന അടിസ്ഥാനം. ഈ മൂന്ന് library-കൾ പഠിച്ചാൽ, NYSE-യിൽ equity-കൾ ട്രേഡ് ചെയ്യുകയാണെങ്കിലും, GaiaEx-ൽ crypto ട്രേഡ് ചെയ്യുകയാണെങ്കിലും, CME-യിൽ derivatives ട്രേഡ് ചെയ്യുകയാണെങ്കിലും—ഏത് market-ഉം analyze ചെയ്യാനും, ഏത് indicator-ഉം build ചെയ്യാനും, ഏത് strategy-ഉം visualize ചെയ്യാനുമുള്ള കഴിവ് നിങ്ങൾക്ക് ലഭിക്കും.