Common Functions trong Dự Án Phân Tích Định Lượng
· 2 min read
Trong một dự án phân tích định lượng, việc xây dựng các hàm dùng chung giúp tiết kiệm thời gian và chuẩn hóa quy trình xử lý dữ liệu, phân tích và giao dịch. Dưới đây là một số nhóm hàm quan trọng.
1. Xử Lý Dữ Liệu
import pandas as pd
import numpy as np
def clean_data(df):
"""Làm sạch dữ liệu: loại bỏ giá trị NaN, trùng lặp."""
df = df.drop_duplicates()
df = df.dropna()
return df
def normalize_data(df, columns):
"""Chuẩn hóa dữ liệu theo min-max scaling."""
for col in columns:
df[col] = (df[col] - df[col].min()) / (df[col].max() - df[col].min())
return df
2. Tải Dữ Liệu từ API
import yfinance as yf
def get_stock_data(ticker, start, end):
"""Tải dữ liệu giá cổ phiếu từ Yahoo Finance."""
stock = yf.download(ticker, start=start, end=end)
return stock
3. Tính Toán Thống Kê Cơ Bản
def moving_average(data, window):
"""Tính trung bình động (Moving Average)"""
return data.rolling(window=window).mean()
def calculate_correlation(df, col1, col2):
"""Tính hệ số tương quan giữa hai cột."""
return df[col1].corr(df[col2])
4. Backtesting Chiến Lược Giao Dịch
def backtest_strategy(prices, signals):
"""Đánh giá hiệu suất chiến lược giao dịch."""
returns = prices.pct_change() * signals.shift(1)
return returns.cumsum()
5. Hiển Thị Dữ Liệu
import matplotlib.pyplot as plt
def plot_stock_prices(df, ticker):
"""Vẽ biểu đồ giá cổ phiếu."""
plt.figure(figsize=(10, 5))
plt.plot(df['Close'], label=f'{ticker} Close Price')
plt.title(f'Giá Cổ Phiếu {ticker}')
plt.xlabel('Thời Gian')
plt.ylabel('Giá')
plt.legend()
plt.show()
Kết Luận
Bộ hàm trên giúp chuẩn hóa quy trình phân tích định lượng, từ việc xử lý dữ liệu, tải dữ liệu, tính toán thống kê đến backtesting chiến lược. Tích hợp các hàm này vào dự án sẽ giúp bạn làm việc hiệu quả hơn.