Python 量化金融與算法交易實戰指南

https://www.python.org/static/community_logos/python-logo-master-v3-TM.png

金融數據獲取與處理

使用yfinance獲取市場數據

python

復制

下載

import yfinance as yf
import pandas as pd# 下載蘋果公司股票數據
aapl = yf.Ticker("AAPL")
hist = aapl.history(period="5y")# 計算移動平均線
hist['MA50'] = hist['Close'].rolling(window=50).mean()
hist['MA200'] = hist['Close'].rolling(window=200).mean()# 可視化
hist[['Close', 'MA50', 'MA200']].plot(figsize=(12, 6))
plt.title('Apple Stock Price with Moving Averages')
plt.ylabel('Price (USD)')
plt.savefig('aapl_ma.png')
plt.show()

https://matplotlib.org/stable/_images/sphx_glr_plot_001.png

使用pandas處理高頻數據

python

復制

下載

# 重采樣高頻數據
intraday = yf.download("AAPL", period="1d", interval="1m")
intraday_5min = intraday.resample('5T').agg({'Open': 'first','High': 'max','Low': 'min','Close': 'last','Volume': 'sum'
})# 計算波動率
intraday_5min['Returns'] = intraday_5min['Close'].pct_change()
intraday_5min['Volatility'] = intraday_5min['Returns'].rolling(12).std() * np.sqrt(252*78)  # 78個5分鐘交易日print(intraday_5min.tail())

技術指標實現

常用指標計算

python

復制

下載

import talib# RSI指標
hist['RSI14'] = talib.RSI(hist['Close'], timeperiod=14)# MACD指標
hist['MACD'], hist['MACD_Signal'], hist['MACD_Hist'] = talib.MACD(hist['Close'], fastperiod=12, slowperiod=26, signalperiod=9
)# Bollinger Bands
hist['UpperBand'], hist['MiddleBand'], hist['LowerBand'] = talib.BBANDS(hist['Close'], timeperiod=20, nbdevup=2, nbdevdn=2
)# 可視化
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8), gridspec_kw={'height_ratios': [3, 1]})
hist[['Close', 'MA50', 'MA200']].plot(ax=ax1)
hist[['RSI14']].plot(ax=ax2)
ax2.axhline(70, color='r', linestyle='--')
ax2.axhline(30, color='g', linestyle='--')
plt.savefig('technical_indicators.png')
plt.show()

回測框架實現

事件驅動回測引擎

python

復制

下載

class BacktestEngine:def __init__(self, data, initial_capital=100000):self.data = dataself.initial_capital = initial_capitalself.positions = []self.current_cash = initial_capitalself.portfolio_values = []def run_backtest(self, strategy):for i, (index, row) in enumerate(self.data.iterrows()):# 獲取當前持倉current_position = self.positions[-1] if self.positions else 0# 執行策略signal = strategy(row, current_position, i)# 執行交易if signal > 0 and current_position <= 0:  # 買入信號position_size = int(self.current_cash / row['Close'])self.positions.append(position_size)self.current_cash -= position_size * row['Close']elif signal < 0 and current_position > 0:  # 賣出信號self.current_cash += current_position * row['Close']self.positions.append(0)else:  # 保持持倉self.positions.append(current_position)# 記錄組合價值portfolio_value = self.current_cash + current_position * row['Close']self.portfolio_values.append(portfolio_value)return self.portfolio_values# 雙均線策略
def dual_moving_average_strategy(data, current_position, index):if index < 200:  # 確保有足夠數據計算MA200return 0if data['MA50'] > data['MA200'] and current_position <= 0:return 1  # 買入信號elif data['MA50'] < data['MA200'] and current_position > 0:return -1  # 賣出信號else:return 0  # 無信號# 運行回測
engine = BacktestEngine(hist)
portfolio_values = engine.run_backtest(dual_moving_average_strategy)

https://matplotlib.org/stable/_images/sphx_glr_plot_002.png

量化交易策略

均值回歸策略

python

復制

下載

def mean_reversion_strategy(data, lookback=20, z_score_threshold=1.0):# 計算滾動統計量data['RollingMean'] = data['Close'].rolling(lookback).mean()data['RollingStd'] = data['Close'].rolling(lookback).std()data['Z-Score'] = (data['Close'] - data['RollingMean']) / data['RollingStd']# 生成交易信號data['Signal'] = 0data.loc[data['Z-Score'] < -z_score_threshold, 'Signal'] = 1  # 買入data.loc[data['Z-Score'] > z_score_threshold, 'Signal'] = -1  # 賣出return data# 應用策略
mr_data = mean_reversion_strategy(hist.copy())
mr_data[['Close', 'RollingMean', 'Z-Score', 'Signal']].plot(secondary_y=['Z-Score', 'Signal'], figsize=(12, 6),style=['-', '--', '-', 'o-']
)
plt.title('Mean Reversion Strategy Signals')
plt.savefig('mean_reversion.png')
plt.show()

動量策略

python

復制

下載

def momentum_strategy(data, lookback=3, hold_period=1):# 計算過去lookback個月的收益率data['Momentum'] = data['Close'].pct_change(lookback * 21)  # 假設21個交易日/月# 生成信號 (每月初調倉)data['Signal'] = 0data.loc[data['Momentum'] > 0, 'Signal'] = 1data.loc[data['Momentum'] <= 0, 'Signal'] = -1# 保持持倉hold_period個月data['Signal'] = data['Signal'].shift(1).rolling(hold_period * 21).mean()return data# 應用策略
momentum_data = momentum_strategy(hist.copy())
momentum_data[['Close', 'Momentum', 'Signal']].plot(secondary_y=['Momentum', 'Signal'], figsize=(12, 6)
)
plt.title('Momentum Strategy Signals')
plt.savefig('momentum.png')
plt.show()

風險管理

投資組合優化

python

復制

下載

import numpy as np
from scipy.optimize import minimize# 獲取多資產收益率
tickers = ['AAPL', 'MSFT', 'GOOG', 'AMZN', 'META']
data = yf.download(tickers, start='2020-01-01', end='2023-01-01')['Adj Close']
returns = data.pct_change().dropna()# 計算協方差矩陣
cov_matrix = returns.cov() * 252  # 年化# 投資組合優化
def portfolio_volatility(weights, cov_matrix):return np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))def optimize_portfolio(returns, cov_matrix):num_assets = len(returns.columns)args = (cov_matrix,)constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})bounds = tuple((0, 1) for asset in range(num_assets))initial_guess = num_assets * [1./num_assets]result = minimize(portfolio_volatility, initial_guess, args=args,method='SLSQP', bounds=bounds, constraints=constraints)return result.xoptimal_weights = optimize_portfolio(returns, cov_matrix)
print("最優權重:", dict(zip(tickers, optimal_weights)))

風險價值(VaR)計算

python

復制

下載

from scipy.stats import normdef calculate_var(returns, confidence_level=0.95):mean = returns.mean()std_dev = returns.std()# 參數法VaRvar_parametric = norm.ppf(1-confidence_level, mean, std_dev)# 歷史模擬法VaRvar_historical = np.percentile(returns, (1-confidence_level)*100)return var_parametric, var_historicalaapl_returns = returns['AAPL']
var_p, var_h = calculate_var(aapl_returns)
print(f"參數法VaR(95%): {var_p:.4f}")
print(f"歷史模擬法VaR(95%): {var_h:.4f}")

實盤交易接口

使用CCXT連接交易所

python

復制

下載

import ccxt
import pandas as pd# 初始化交易所連接
exchange = ccxt.binance({'apiKey': 'YOUR_API_KEY','secret': 'YOUR_SECRET','enableRateLimit': True
})# 獲取K線數據
ohlcv = exchange.fetch_ohlcv('BTC/USDT', '1d', limit=100)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')# 下訂單示例
def place_limit_order(symbol, side, amount, price):try:order = exchange.create_order(symbol=symbol,type='limit',side=side,amount=amount,price=price)print(f"訂單已提交: {order['id']}")return orderexcept Exception as e:print(f"下單失敗: {str(e)}")return None# 獲取賬戶余額
balance = exchange.fetch_balance()
print("USDT余額:", balance['USDT']['free'])

https://camo.githubusercontent.com/9e37b5d39a9e0e4b6b6a3f7b5e9d5d5e5b5e5d5e5/68747470733a2f2f636378742e696f2f696d672f65786368616e6765732e706e67

高頻交易策略

訂單簿分析

python

復制

下載

import numpy as npdef analyze_order_book(order_book, depth=10):bids = np.array(order_book['bids'][:depth])asks = np.array(order_book['asks'][:depth])# 計算買賣價差spread = asks[0][0] - bids[0][0]mid_price = (asks[0][0] + bids[0][0]) / 2# 計算市場深度bid_depth = bids[:, 0] * bids[:, 1]ask_depth = asks[:, 0] * asks[:, 1]return {'spread': spread,'mid_price': mid_price,'bid_depth': bid_depth.sum(),'ask_depth': ask_depth.sum(),'imbalance': (bid_depth.sum() - ask_depth.sum()) / (bid_depth.sum() + ask_depth.sum())}# 獲取訂單簿數據
order_book = exchange.fetch_order_book('BTC/USDT')
ob_metrics = analyze_order_book(order_book)
print("訂單簿指標:", ob_metrics)

簡單做市策略

python

復制

下載

class MarketMaker:def __init__(self, exchange, symbol, position_limit=10):self.exchange = exchangeself.symbol = symbolself.position_limit = position_limitself.orders = []def run_strategy(self, spread_pct=0.001, order_size=0.1):# 獲取當前市場價格ticker = self.exchange.fetch_ticker(self.symbol)mid_price = (ticker['bid'] + ticker['ask']) / 2# 計算買賣價格bid_price = mid_price * (1 - spread_pct)ask_price = mid_price * (1 + spread_pct)# 獲取當前持倉balance = self.exchange.fetch_balance()position = balance.get(self.symbol.split('/')[0], {}).get('free', 0)# 取消所有未成交訂單self.cancel_all_orders()# 下新訂單if position < self.position_limit:bid_order = self.exchange.create_limit_buy_order(self.symbol, order_size, bid_price)self.orders.append(bid_order['id'])if position > -self.position_limit:ask_order = self.exchange.create_limit_sell_order(self.symbol, order_size, ask_price)self.orders.append(ask_order['id'])def cancel_all_orders(self):for order_id in self.orders:try:self.exchange.cancel_order(order_id, self.symbol)except:continueself.orders = []# 使用示例
mm = MarketMaker(exchange, 'BTC/USDT')
mm.run_strategy()

機器學習在量化中的應用

特征工程

python

復制

下載

from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_splitdef create_features(data, lags=5):# 基礎特征data['Returns'] = data['Close'].pct_change()data['Volatility'] = data['Returns'].rolling(21).std()data['Momentum'] = data['Close'] / data['Close'].shift(21) - 1# 滯后特征for lag in range(1, lags+1):data[f'Return_lag_{lag}'] = data['Returns'].shift(lag)# 技術指標data['RSI14'] = talib.RSI(data['Close'], timeperiod=14)data['MACD'], _, _ = talib.MACD(data['Close'])# 目標變量 (未來5天收益率)data['Target'] = data['Close'].shift(-5) / data['Close'] - 1return data.dropna()# 準備數據
featured_data = create_features(hist.copy())
X = featured_data.drop(['Target', 'Open', 'High', 'Low', 'Close', 'Volume'], axis=1)
y = np.where(featured_data['Target'] > 0, 1, 0)  # 分類問題# 標準化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)# 劃分數據集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, shuffle=False)

預測模型構建

python

復制

下載

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score
import xgboost as xgb# 隨機森林模型
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
y_pred_rf = rf.predict(X_test)
print("隨機森林準確率:", accuracy_score(y_test, y_pred_rf))# XGBoost模型
xgb_model = xgb.XGBClassifier(n_estimators=100, learning_rate=0.1)
xgb_model.fit(X_train, y_train)
y_pred_xgb = xgb_model.predict(X_test)
print("XGBoost準確率:", accuracy_score(y_test, y_pred_xgb))# 特征重要性
plt.figure(figsize=(10, 6))
pd.Series(xgb_model.feature_importances_, index=X.columns).sort_values().plot(kind='barh')
plt.title('Feature Importance')
plt.savefig('feature_importance.png')
plt.show()

結語與學習路徑

https://www.python.org/static/community_logos/python-powered-h-140x182.png

通過這九篇系列教程,你已經掌握了:

  1. 金融數據獲取與處理技術

  2. 技術指標實現與可視化

  3. 回測框架設計與策略評估

  4. 經典量化交易策略實現

  5. 投資組合優化與風險管理

  6. 實盤交易接口使用

  7. 高頻交易策略基礎

  8. 機器學習在量化中的應用

進階學習方向

  1. 深入量化領域

    • 市場微觀結構研究

    • 期權定價與波動率交易

    • 套利策略開發

  2. 技術深化

    • C++/Rust擴展性能關鍵部分

    • 分布式回測系統構建

    • 強化學習在交易中的應用

  3. 專業認證

    • CFA (特許金融分析師)

    • FRM (金融風險管理師)

    • CMT (特許市場技術分析師)

  4. 實盤經驗

    • 從小資金開始實盤測試

    • 參與量化交易比賽

    • 加入量化對沖基金團隊

量化交易是金融與技術的完美結合,Python作為這一領域的核心工具,將持續發揮重要作用。保持學習,你將成為市場的敏銳捕手!

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/85624.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/85624.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/85624.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【StarRocks系列】join查詢優化

目錄 Join 類型 和 Join 策略 1. Join 類型&#xff08;Join Type&#xff09; 2. Join 策略&#xff08;Join Strategy&#xff09; 分布式 Join 策略 (核心) 1. Colocate Join (本地 Join - 最優): 2. Bucket Shuffle Join: 3. Broadcast Join (復制廣播): 4. Shuffl…

【論文解讀】ZeroSearch: 零API成本激活大模型Web搜索

1st author: Hao Sun 孫浩 - PhD Candidate Peking University - Homepage paper: [2505.04588] ZeroSearch: Incentivize the Search Capability of LLMs without Searching code: Alibaba-NLP/ZeroSearch: ZeroSearch: Incentivize the Search Capability of LLMs without…

JAVA網絡編程中HTTP客戶端(HttpURLConnection、Apache HttpClient)

HTTP 客戶端是 Java 中實現網絡請求的核心工具,主要用于與 Web 服務器交互(如獲取網頁、提交表單、調用 REST API 等)。Java 生態中有兩種主流的 HTTP 客戶端實現:??HttpURLConnection(JDK 原生)?? 和 ??Apache HttpClient(第三方庫)??。以下是兩者的詳細解析、…

C# Process.Start多個參數傳遞及各個參數之間的空格處理

最近做一個軟件集成的事情&#xff0c;有多個之前做的軟件&#xff0c;集成到一起自己用&#xff0c;使用了 Process.Start&#xff08;“*.exe”&#xff09;的方式&#xff0c;然而遇到了傳遞參數的問題。 這里匯總后的程序叫main.exe&#xff0c;要匯總的軟件之一是pro1.…

【Python】Excel表格操作:ISBN轉條形碼

一、效果 原始文件&#xff1a; 輸出文件&#xff1a; 二、代碼 import os import logging from openpyxl import load_workbook from openpyxl.drawing.image import Image as ExcelImage from barcode import EAN13 from barcode.writer import ImageWriterlogging.basicCo…

【Fargo】mediasoup發送2:碼率分配、傳輸基類設計及WebRtcTransport原理

Fargo 使用了mediasoup的代碼,搬運了他的架構架構精妙,但是似乎是為了sfu而生,【Fargo】mediasoup發送1:控制與數據分離的分層設計和原理我本地用來發送測試,因此需要進一步梳理: 通過分析這段代碼,我來詳細解釋: 一、sfu 需要碼率級別的分配控制 1. DistributeAvail…

矩陣置零C++

給定一個 m x n 的矩陣&#xff0c;如果一個元素為 0 &#xff0c;則將其所在行和列的所有元素都設為 0 。請使用 原地 算法。 思路&#xff1a; 1、讓首行首列記錄哪一行哪一列有0 2、于是可以直接遍歷非首行首列的元素&#xff0c;若該元素對應的首行首列為0&#xff0c;說明…

大內存對電腦性能有哪些提升

在科技飛速發展的今天&#xff0c;電腦已經成為我們生活和工作中不可或缺的伙伴。無論是日常辦公、追劇娛樂&#xff0c;還是進行復雜的游戲和專業設計&#xff0c;電腦的性能都至關重要。而在影響電腦性能的眾多因素中&#xff0c;內存大小常常被人們忽視。 多任務處理更流暢…

【StarRocks系列】Update語句

目錄 簡要流程 詳細流程 1. UPDATE 語句執行流程 2. 如何更新表的數據 3. 是否支持事務 總結關鍵點 簡要流程 前端處理&#xff08;FE&#xff09;&#xff1a; 解析 SQL 并驗證主鍵條件生成包含主鍵列表和新值的更新計劃按主鍵哈希分發到對應 BE 后端執行&#xff08…

計算機三級Linux應用與開發

第 1 章 計算機體系結構與操作系統 1.1 計算科學與計算機系統 馮諾依曼體系的結構要點&#xff1a; 計算機數制采用二進制&#xff0c;程序指令和數據統一存儲&#xff0c;計算機應按照程序順序執行。按照馮諾依曼結構設計的計算機由 控制器&#xff0c;運算器&#xff0c;存…

Web攻防-XSS跨站Cookie盜取數據包提交網絡釣魚BEEF項目XSS平臺危害利用

知識點&#xff1a; 1、Web攻防-XSS跨站-手工代碼&框架工具&在線平臺 2、Web攻防-XSS跨站-Cookie盜取&數據提交&網絡釣魚 演示案例-WEB攻防-XSS跨站-Cookie盜取&數據提交&網絡釣魚&Beef工具 1、XSS跨站-攻擊利用-憑據盜取 條件&#xff1a;無防…

自力更生式養老VS三大新型養老:在時代裂變中重構銀發生存法則

在歲月長河中&#xff0c;父母曾為子女遮風擋雨&#xff0c;當他們步入暮年&#xff0c;養老問題成為家庭與社會共同關注的焦點。 “父母的養老終究是自力更生”&#xff0c;這句話道出了養老的本質內核。 然而&#xff0c;在自力更生的基礎上&#xff0c;選擇合適的養老方式…

計算機網絡學習筆記:Wireshark觀察TCP通信

文章目錄 前言一、前置準備二、三報文握手過程抓包2.1、第一次握手2.2、第二次握手2.3、第三次握手 三、通信過程抓包3.1、報文 44379 – 客戶端發數據&#xff08;PSH, ACK&#xff09;3.2、 報文 44380 – 服務端確認收到數據&#xff08;ACK&#xff09;3.3、報文 44469 – …

在Linux中,Iptables能做什么?

概述 背景說明 在運維工作中&#xff0c;Iptables是一個不可或缺的工具&#xff0c;它提供了強大的網絡流量控制和管理能力。 問題呈現 iptables是一個不可獲取的工具&#xff0c;你對其了解多少&#xff1f;該工具你是否真的會用&#xff1f;詳細功能對應的應用場景你是否…

Linux——linux的基本命令

目錄 一、linux的目錄結構 二、絕對路徑和相對路徑 三、文件類型&#xff08;linux下所有東西都可看作文件&#xff09; 四、文件的權限 五、文件權限的修改&#xff08;chmod&#xff09; 六、linux常用的命令 七、文件查看命令 八、文件編輯命令 九、文件壓縮與解壓…

智慧水利數字孿生解決方案:百川孿生智領千行,100+標桿案例賦能智慧水利全域升級

在數字技術革命與產業變革深度交織的浪潮下&#xff0c;智慧水利作為保障國家水安全、推動水利高質量發展的核心載體&#xff0c;正以數字孿生技術為引擎&#xff0c;驅動水利行業從“經驗驅動”向“數據驅動”轉型。 山東融谷作為智慧水利數字孿生領域的創新實踐者&#xff0c…

深入解析ID3算法:信息熵驅動的決策樹構建基石

本文來自「大千AI助手」技術實戰系列&#xff0c;專注用真話講技術&#xff0c;拒絕過度包裝。 ID3&#xff08;Iterative Dichotomiser 3&#xff09; 是機器學習史上的里程碑算法&#xff0c;由Ross Quinlan于1986年提出。它首次將信息論引入決策樹構建&#xff0c;奠定了現代…

Java解析audio時長

前提需要電腦上先安裝后ffmpeg public long parseDuration(String audioPath) {long durationMs -1;try {Process process Runtime.getRuntime().exec("ffprobe " audioPath);// InputStream is process.getInputStream();InputStream is process.getErrorStrea…

python學智能算法(十五)|機器學習樸素貝葉斯方法進階-CountVectorizer多文本處理

【1】引言 前序學習進程中&#xff0c;已經學習CountVectorizer文本處理的簡單技巧&#xff0c;先相關文章鏈接為&#xff1a; python學智能算法&#xff08;十四&#xff09;|機器學習樸素貝葉斯方法進階-CountVectorizer文本處理簡單測試-CSDN博客 此次繼續深入&#xff0…

AiPy 監控視頻智能監察:人像一鍵抽取+可反復執行程序落地

兄弟們&#xff0c;不知道你們有沒有過查監控的經歷&#xff0c;雖然現在監控攝像頭是越來越多&#xff0c;硬盤越塞越滿&#xff0c;但真出了事兒&#xff0c;回放查錄像堪比大海撈針&#xff01;純人工一幀幀的去找&#xff0c;能把眼睛盯瞎還是人影都找不到。不過我最近搞了…