Created
September 9, 2025 02:48
-
-
Save oxfordyang2016/525f1da272a7def62622ec76475f597a to your computer and use it in GitHub Desktop.
qlib中的启动代码展示信号的
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from pyqlib import init | |
| from qlib.data import D | |
| import matplotlib.pyplot as plt | |
| import pandas as pd | |
| import numpy as np | |
| # 初始化 | |
| provider = r"D:\investmentresearch\qlibsystem\data_commod_daily\qlib_data_demo" | |
| init(provider_uri=provider) | |
| symbol = "CU_DOMINANT_DAILY" | |
| # 取收盘价 | |
| df = D.features([symbol], ["$close"], start_time="2018-01-02", end_time="2019-12-31") | |
| close = df["$close"] | |
| # 计算短期/长期均线 | |
| ma5 = close.rolling(5).mean() | |
| ma20 = close.rolling(20).mean() | |
| # 策略信号 | |
| signal = (ma5 > ma20).astype(int) | |
| # 日收益率 | |
| ret = close.pct_change().fillna(0) | |
| # 策略收益 | |
| strategy_ret = signal.shift(1) * ret | |
| nav_strategy = (1 + strategy_ret).cumprod() | |
| # 基准:买入持有 | |
| nav_bh = (1 + ret).cumprod() | |
| # 夏普比率计算函数 | |
| def sharpe_ratio(returns, freq=252): | |
| mean_ret = returns.mean() | |
| vol = returns.std() | |
| return (mean_ret / vol) * np.sqrt(freq) if vol > 0 else np.nan | |
| # 计算夏普 | |
| sharpe_strategy = sharpe_ratio(strategy_ret) | |
| sharpe_bh = sharpe_ratio(ret) | |
| print(f"Sharpe Ratio (MA策略): {sharpe_strategy:.2f}") | |
| print(f"Sharpe Ratio (买入持有): {sharpe_bh:.2f}") | |
| # 对比画图 | |
| plt.figure(figsize=(10,5)) | |
| nav_strategy.plot(label="MA Crossover Strategy") | |
| nav_bh.plot(label="Buy & Hold") | |
| plt.title(f"Strategy vs Buy&Hold - {symbol}") | |
| plt.ylabel("Net Value") | |
| plt.legend() | |
| plt.grid(True) | |
| plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment