Bài viết gần đây
-
-
So sánh Flutter và React Native
Tháng mười một 17, 2025 -
So sánh Flutter và React Native
Tháng mười một 17, 2025 -
Chiến lược RSI 30–70 trong Bot Auto Trading Python
Tháng mười một 17, 2025 -
Chiến Lược Giao Dịch News Filter sử dụng API Python
Tháng mười một 17, 2025
| NumPy Được Sử Dụng Trong Phân Tích Dữ Liệu Tài Chính – Hướng Dẫn Chi Tiết
Được viết bởi thanhdt vào ngày 15/11/2025 lúc 20:18 | 10 lượt xem
NumPy Được Sử Dụng Trong Phân Tích Dữ Liệu Tài Chính
NumPy (Numerical Python) là thư viện cơ bản và quan trọng nhất trong phân tích dữ liệu tài chính với Python. Bài viết này sẽ hướng dẫn bạn cách sử dụng NumPy để phân tích dữ liệu tài chính một cách hiệu quả.
import numpy as np
Tại Sao Sử Dụng NumPy?
NumPy cung cấp:
- Hiệu suất cao: Tính toán nhanh hơn Python thuần 10-100 lần
- Mảng đa chiều: Xử lý dữ liệu tài chính dễ dàng
- Hàm toán học phong phú: Từ cơ bản đến nâng cao
- Tích hợp tốt: Làm nền tảng cho Pandas, SciPy, Matplotlib
- Tối ưu bộ nhớ: Xử lý dữ liệu lớn hiệu quả
1. Tạo và Xử Lý Mảng Dữ Liệu Giá
Tạo Mảng Giá Từ Dữ Liệu
import numpy as np
# Dữ liệu giá đóng cửa (Close prices)
prices = np.array([100, 102, 101, 105, 103, 107, 106, 108, 110, 109])
print("Giá đóng cửa:", prices)
print("Kiểu dữ liệu:", prices.dtype)
print("Kích thước:", prices.shape)
# Tạo mảng 2D cho OHLC (Open, High, Low, Close)
ohlc_data = np.array([
[100, 103, 99, 102], # Ngày 1
[102, 104, 101, 101], # Ngày 2
[101, 105, 100, 105], # Ngày 3
[105, 107, 104, 103], # Ngày 4
[103, 108, 102, 107] # Ngày 5
])
print("\nDữ liệu OHLC:")
print(ohlc_data)
print("Kích thước:", ohlc_data.shape)
Truy Cập Dữ Liệu
# Lấy cột giá đóng cửa
close_prices = ohlc_data[:, -1]
print("Giá đóng cửa:", close_prices)
# Lấy giá cao nhất
high_prices = ohlc_data[:, 1]
print("Giá cao nhất:", high_prices)
# Lấy giá thấp nhất
low_prices = ohlc_data[:, 2]
print("Giá thấp nhất:", low_prices)
2. Tính Toán Thay Đổi Giá
Tính Phần Trăm Thay Đổi
price_changes = np.diff(prices) / prices[:-1] * 100
print("Thay đổi giá (%):", price_changes)
log_returns = np.diff(np.log(prices)) * 100
print("Log returns (%):", log_returns)
cumulative_returns = np.cumsum(log_returns)
print("Lợi nhuận tích lũy (%):", cumulative_returns)
Tính Giá Trung Bình và Độ Lệch
mean_price = np.mean(prices)
print(f"Giá trung bình: ${mean_price:.2f}")
median_price = np.median(prices)
print(f"Giá trung vị: ${median_price:.2f}")
std_price = np.std(prices)
print(f"Độ lệch chuẩn: ${std_price:.2f}")
variance = np.var(prices)
print(f"Phương sai: ${variance:.2f}")
3. Tính Toán Chỉ Báo Kỹ Thuật
Moving Average (Trung Bình Động)
def moving_average(prices, window):
return np.convolve(prices, np.ones(window)/window, mode='valid')
sma_5 = moving_average(prices, 5)
print("SMA 5 ngày:", sma_5)
sma_10 = moving_average(prices, 10)
print("SMA 10 ngày:", sma_10)
Exponential Moving Average (EMA)
def exponential_moving_average(prices, alpha):
ema = np.zeros_like(prices)
ema[0] = prices[0]
for i in range(1, len(prices)):
ema[i] = alpha * prices[i] + (1 - alpha) * ema[i-1]
return ema
ema_9 = exponential_moving_average(prices, 0.2)
print("EMA 9 ngày:", ema_9)
RSI
def calculate_rsi(prices, period=14):
deltas = np.diff(prices)
gains = np.where(deltas > 0, deltas, 0)
losses = np.where(deltas < 0, -deltas, 0)
avg_gains = moving_average_cumsum(gains, period)
avg_losses = moving_average_cumsum(losses, period)
rs = np.where(avg_losses != 0, avg_gains / avg_losses, 0)
rsi = 100 - (100 / (1 + rs))
return rsi
rsi = calculate_rsi(prices, 14)
print("RSI:", rsi)
MACD
def calculate_macd(prices, fast_period=12, slow_period=26, signal_period=9):
fast_alpha = 2 / (fast_period + 1)
slow_alpha = 2 / (slow_period + 1)
signal_alpha = 2 / (signal_period + 1)
ema_fast = exponential_moving_average(prices, fast_alpha)
ema_slow = exponential_moving_average(prices, slow_alpha)
macd_line = ema_fast - ema_slow
signal_line = exponential_moving_average(macd_line, signal_alpha)
histogram = macd_line - signal_line
return macd_line, signal_line, histogram
macd, signal, hist = calculate_macd(prices)
print("MACD line:", macd[-5:])
print("Signal line:", signal[-5:])
print("Histogram:", hist[-5:])
Bollinger Bands
def bollinger_bands(prices, window=20, num_std=2):
sma = moving_average_cumsum(prices, window)
std = np.zeros(len(sma))
for i in range(len(sma)):
std[i] = np.std(prices[i:i+window])
upper_band = sma + (num_std * std)
lower_band = sma - (num_std * std)
return sma, upper_band, lower_band
4. Phân Tích Rủi Ro
Tính Volatility
log_returns = np.diff(np.log(prices))
volatility = np.std(log_returns) * np.sqrt(252)
print(f"Volatility hàng năm: {volatility * 100:.2f}%")
VaR
def calculate_var(returns, confidence_level=0.05):
return np.percentile(returns, confidence_level * 100)
returns = np.diff(prices) / prices[:-1]
var_5 = calculate_var(returns)
print(f"VaR 5%: {var_5 * 100:.2f}%")
Maximum Drawdown
def maximum_drawdown(prices):
cumulative = np.cumprod(1 + np.diff(prices) / prices[:-1])
running_max = np.maximum.accumulate(cumulative)
drawdown = (cumulative - running_max) / running_max
max_dd = np.min(drawdown)
return max_dd, drawdown
📉 5. Phân Tích Tương Quan
returns_matrix = np.column_stack([
returns1, returns2, returns3
])
correlation_matrix = np.corrcoef(returns_matrix.T)
print(correlation_matrix)
6. Tối Ưu Hóa Danh Mục
optimal_weights = (1 / risk_aversion) * inv_cov @ expected_returns
optimal_weights /= np.sum(optimal_weights)
print(optimal_weights)
7. Xử Lý Dữ Liệu Thiếu và Ngoại Lai
prices_filled = np.where(np.isnan(prices_with_nan), mean_price, prices_with_nan)
8. Tính Hiệu Suất
metrics = calculate_performance_metrics(prices)
print(metrics)
9. Tối Ưu Hóa Hiệu Suất
result_vectorized = np.diff(large_prices)
10. Ví Dụ Thực Tế: Crypto
print("=== Phân Tích BTC ===")
Kết Luận
NumPy là công cụ không thể thiếu trong phân tích dữ liệu tài chính.
- Tính toán nhanh
- Hàm toán học phong phú
- Phân tích rủi ro mạnh
- Tối ưu hóa danh mục
Bài viết được biên soạn bởi CoinGetMarket