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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈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;能把眼睛盯瞎还是人影都找不到。不过我最近搞了…