diff --git a/course/01-introduction.md b/course/Full Algorithmic Trading Using Python/01-introduction.md similarity index 100% rename from course/01-introduction.md rename to course/Full Algorithmic Trading Using Python/01-introduction.md diff --git a/course/02-episode-2.md b/course/Full Algorithmic Trading Using Python/02-episode-2.md similarity index 100% rename from course/02-episode-2.md rename to course/Full Algorithmic Trading Using Python/02-episode-2.md diff --git a/course/03-key-concepts.md b/course/Full Algorithmic Trading Using Python/03-key-concepts.md similarity index 100% rename from course/03-key-concepts.md rename to course/Full Algorithmic Trading Using Python/03-key-concepts.md diff --git a/course/04-handling-data.md b/course/Full Algorithmic Trading Using Python/04-handling-data.md similarity index 100% rename from course/04-handling-data.md rename to course/Full Algorithmic Trading Using Python/04-handling-data.md diff --git a/course/05-trading-and-orders.md b/course/Full Algorithmic Trading Using Python/05-trading-and-orders.md similarity index 100% rename from course/05-trading-and-orders.md rename to course/Full Algorithmic Trading Using Python/05-trading-and-orders.md diff --git a/course/06-indicators-history.md b/course/Full Algorithmic Trading Using Python/06-indicators-history.md similarity index 100% rename from course/06-indicators-history.md rename to course/Full Algorithmic Trading Using Python/06-indicators-history.md diff --git a/course/07-consolidators-rolling-windows.md b/course/Full Algorithmic Trading Using Python/07-consolidators-rolling-windows.md similarity index 100% rename from course/07-consolidators-rolling-windows.md rename to course/Full Algorithmic Trading Using Python/07-consolidators-rolling-windows.md diff --git a/course/08-dynamic-universes.md b/course/Full Algorithmic Trading Using Python/08-dynamic-universes.md similarity index 100% rename from course/08-dynamic-universes.md rename to course/Full Algorithmic Trading Using Python/08-dynamic-universes.md diff --git a/course/09-twitter-trading-bot.md b/course/Full Algorithmic Trading Using Python/09-twitter-trading-bot.md similarity index 100% rename from course/09-twitter-trading-bot.md rename to course/Full Algorithmic Trading Using Python/09-twitter-trading-bot.md diff --git a/course/10-backtesting-performance.md b/course/Full Algorithmic Trading Using Python/10-backtesting-performance.md similarity index 100% rename from course/10-backtesting-performance.md rename to course/Full Algorithmic Trading Using Python/10-backtesting-performance.md diff --git a/course/11-forex-trading.md b/course/Full Algorithmic Trading Using Python/11-forex-trading.md similarity index 100% rename from course/11-forex-trading.md rename to course/Full Algorithmic Trading Using Python/11-forex-trading.md diff --git a/course/12-options-trading.md b/course/Full Algorithmic Trading Using Python/12-options-trading.md similarity index 100% rename from course/12-options-trading.md rename to course/Full Algorithmic Trading Using Python/12-options-trading.md diff --git a/course/13-options-code-along.md b/course/Full Algorithmic Trading Using Python/13-options-code-along.md similarity index 100% rename from course/13-options-code-along.md rename to course/Full Algorithmic Trading Using Python/13-options-code-along.md diff --git a/course/14-crypto-trading-bots.md b/course/Full Algorithmic Trading Using Python/14-crypto-trading-bots.md similarity index 100% rename from course/14-crypto-trading-bots.md rename to course/Full Algorithmic Trading Using Python/14-crypto-trading-bots.md diff --git a/course/15-algorithm-framework.md b/course/Full Algorithmic Trading Using Python/15-algorithm-framework.md similarity index 100% rename from course/15-algorithm-framework.md rename to course/Full Algorithmic Trading Using Python/15-algorithm-framework.md diff --git a/course/16-data-driven-research.md b/course/Full Algorithmic Trading Using Python/16-data-driven-research.md similarity index 100% rename from course/16-data-driven-research.md rename to course/Full Algorithmic Trading Using Python/16-data-driven-research.md diff --git a/course/17-bitcoin-ml-bot.md b/course/Full Algorithmic Trading Using Python/17-bitcoin-ml-bot.md similarity index 100% rename from course/17-bitcoin-ml-bot.md rename to course/Full Algorithmic Trading Using Python/17-bitcoin-ml-bot.md diff --git a/course/18-live-trading.md b/course/Full Algorithmic Trading Using Python/18-live-trading.md similarity index 100% rename from course/18-live-trading.md rename to course/Full Algorithmic Trading Using Python/18-live-trading.md diff --git a/course/19-trading-bot-50-lines.md b/course/Full Algorithmic Trading Using Python/19-trading-bot-50-lines.md similarity index 100% rename from course/19-trading-bot-50-lines.md rename to course/Full Algorithmic Trading Using Python/19-trading-bot-50-lines.md diff --git a/course/Full Algorithmic Trading Using Python/README.md b/course/Full Algorithmic Trading Using Python/README.md new file mode 100644 index 0000000..efd46e9 --- /dev/null +++ b/course/Full Algorithmic Trading Using Python/README.md @@ -0,0 +1,37 @@ +# Full Algorithmic Trading Using Python — 课程教程 + +> 本目录是对 YouTube 频道 **TradeOptionsWithMe** 的《Full Algorithmic Trading Using Python》系列的**学习笔记 + 视频归档**。 +> 播放列表:https://youtube.com/playlist?list=PLtqRgJ_TIq8Y6YG8-G-ETIFW_36mvxMLad + +- **集数**:19 集 | **总时长**:约 6 小时 45 分 +- **每集内容**:📌 中文要点导读(提炼) + 📝 英文完整文稿(本地 ASR 转写) + 🎬 本地视频(360p) +- **提醒**:文稿由自动语音识别生成,**未人工校对**;仅供个人学习检索,版权归原作者所有。视频画质上限 360p(YouTube 未登录下载限制)。 + +## 目录 + +| 集 | 标题 | 时长 | 链接 | +|---|---|---|---| +| 01 | Introduction(课程总览) | 7:19 | [📄 笔记](01-introduction.md) · [🎬 视频](videos/01-introduction.mp4) | +| 02 | How Trading Algorithms Work(算法原理与开发流程) | 10:03 | [📄 笔记](02-episode-2.md) · [🎬 视频](videos/02-episode-2.mp4) | +| 03 | Key Concepts(关键概念:时间处理·骨架·Symbol) | 10:05 | [📄 笔记](03-key-concepts.md) · [🎬 视频](videos/03-key-concepts.mp4) | +| 04 | Handling Data(处理数据 · 第一个算法) | 18:01 | [📄 笔记](04-handling-data.md) · [🎬 视频](videos/04-handling-data.mp4) | +| 05 | Trading & Orders(下单、订单管理与调试) | 28:46 | [📄 笔记](05-trading-and-orders.md) · [🎬 视频](videos/05-trading-and-orders.mp4) | +| 06 | Indicators & Historical Data(指标与历史数据) | 28:32 | [📄 笔记](06-indicators-history.md) · [🎬 视频](videos/06-indicators-history.mp4) | +| 07 | Consolidators & Rolling Windows(合并器、滚动窗口、事件调度) | 22:40 | [📄 笔记](07-consolidators-rolling-windows.md) · [🎬 视频](videos/07-consolidators-rolling-windows.mp4) | +| 08 | Dynamic Universes(动态证券池与基本面选股) | 25:30 | [📄 笔记](08-dynamic-universes.md) · [🎬 视频](videos/08-dynamic-universes.mp4) | +| 09 | Twitter Trading Bot(自定义数据 · 推文情绪) | 26:52 | [📄 笔记](09-twitter-trading-bot.md) · [🎬 视频](videos/09-twitter-trading-bot.mp4) | +| 10 | Backtesting & Performance Analysis(回测与绩效评估) | 25:45 | [📄 笔记](10-backtesting-performance.md) · [🎬 视频](videos/10-backtesting-performance.mp4) | +| 11 | Forex Trading(外汇 · 均值回归) | 13:27 | [📄 笔记](11-forex-trading.md) · [🎬 视频](videos/11-forex-trading.mp4) | +| 12 | Options Trading(期权入门) | 15:28 | [📄 笔记](12-options-trading.md) · [🎬 视频](videos/12-options-trading.mp4) | +| 13 | Options Code-Along(保护性看跌期权实战) | 26:06 | [📄 笔记](13-options-code-along.md) · [🎬 视频](videos/13-options-code-along.mp4) | +| 14 | Crypto Trading Bots(加密货币 · RSI 动量) | 15:51 | [📄 笔记](14-crypto-trading-bots.md) · [🎬 视频](videos/14-crypto-trading-bots.mp4) | +| 15 | The Algorithm Framework(算法框架) | 34:14 | [📄 笔记](15-algorithm-framework.md) · [🎬 视频](videos/15-algorithm-framework.mp4) | +| 16 | Data-Driven Research(研究环境 · QuantBook) | 21:52 | [📄 笔记](16-data-driven-research.md) · [🎬 视频](videos/16-data-driven-research.mp4) | +| 17 | Bitcoin ML Bot(用神经网络做比特币) | 31:07 | [📄 笔记](17-bitcoin-ml-bot.md) · [🎬 视频](videos/17-bitcoin-ml-bot.mp4) | +| 18 | How to Live Trade(实盘部署与 Paper Trading) | 26:03 | [📄 笔记](18-live-trading.md) · [🎬 视频](videos/18-live-trading.mp4) | +| 19 | 50-Line Trading Bot(50 行代码 · 标普成分股调整) | 17:29 | [📄 笔记](19-trading-bot-50-lines.md) · [🎬 视频](videos/19-trading-bot-50-lines.mp4) | + +## 关于本归档 +- 视频:经 yt-dlp 下载归档(360p),讲稿:faster-whisper 本地转写,导读:小五整理。 +- 系列主线为 **Python + QuantConnect(Lean 引擎)** 开发算法交易:从概念 → 下单/指标/数据 → 各类资产(股/汇/期权/币)→ 框架/研究/ML → 实盘。 +- 生成日期:2026-09-12。 diff --git a/course/videos/01-introduction.mp4 b/course/Full Algorithmic Trading Using Python/videos/01-introduction.mp4 similarity index 100% rename from course/videos/01-introduction.mp4 rename to course/Full Algorithmic Trading Using Python/videos/01-introduction.mp4 diff --git a/course/videos/02-episode-2.mp4 b/course/Full Algorithmic Trading Using Python/videos/02-episode-2.mp4 similarity index 100% rename from course/videos/02-episode-2.mp4 rename to course/Full Algorithmic Trading Using Python/videos/02-episode-2.mp4 diff --git a/course/videos/03-key-concepts.mp4 b/course/Full Algorithmic Trading Using Python/videos/03-key-concepts.mp4 similarity index 100% rename from course/videos/03-key-concepts.mp4 rename to course/Full Algorithmic Trading Using Python/videos/03-key-concepts.mp4 diff --git a/course/videos/04-handling-data.mp4 b/course/Full Algorithmic Trading Using Python/videos/04-handling-data.mp4 similarity index 100% rename from course/videos/04-handling-data.mp4 rename to course/Full Algorithmic Trading Using Python/videos/04-handling-data.mp4 diff --git a/course/videos/05-trading-and-orders.mp4 b/course/Full Algorithmic Trading Using Python/videos/05-trading-and-orders.mp4 similarity index 100% rename from course/videos/05-trading-and-orders.mp4 rename to course/Full Algorithmic Trading Using Python/videos/05-trading-and-orders.mp4 diff --git a/course/videos/06-indicators-history.mp4 b/course/Full Algorithmic Trading Using Python/videos/06-indicators-history.mp4 similarity index 100% rename from course/videos/06-indicators-history.mp4 rename to course/Full Algorithmic Trading Using Python/videos/06-indicators-history.mp4 diff --git a/course/videos/07-consolidators-rolling-windows.mp4 b/course/Full Algorithmic Trading Using Python/videos/07-consolidators-rolling-windows.mp4 similarity index 100% rename from course/videos/07-consolidators-rolling-windows.mp4 rename to course/Full Algorithmic Trading Using Python/videos/07-consolidators-rolling-windows.mp4 diff --git a/course/videos/08-dynamic-universes.mp4 b/course/Full Algorithmic Trading Using Python/videos/08-dynamic-universes.mp4 similarity index 100% rename from course/videos/08-dynamic-universes.mp4 rename to course/Full Algorithmic Trading Using Python/videos/08-dynamic-universes.mp4 diff --git a/course/videos/09-twitter-trading-bot.mp4 b/course/Full Algorithmic Trading Using Python/videos/09-twitter-trading-bot.mp4 similarity index 100% rename from course/videos/09-twitter-trading-bot.mp4 rename to course/Full Algorithmic Trading Using Python/videos/09-twitter-trading-bot.mp4 diff --git a/course/videos/10-backtesting-performance.mp4 b/course/Full Algorithmic Trading Using Python/videos/10-backtesting-performance.mp4 similarity index 100% rename from course/videos/10-backtesting-performance.mp4 rename to course/Full Algorithmic Trading Using Python/videos/10-backtesting-performance.mp4 diff --git a/course/videos/11-forex-trading.mp4 b/course/Full Algorithmic Trading Using Python/videos/11-forex-trading.mp4 similarity index 100% rename from course/videos/11-forex-trading.mp4 rename to course/Full Algorithmic Trading Using Python/videos/11-forex-trading.mp4 diff --git a/course/videos/12-options-trading.mp4 b/course/Full Algorithmic Trading Using Python/videos/12-options-trading.mp4 similarity index 100% rename from course/videos/12-options-trading.mp4 rename to course/Full Algorithmic Trading Using Python/videos/12-options-trading.mp4 diff --git a/course/videos/13-options-code-along.mp4 b/course/Full Algorithmic Trading Using Python/videos/13-options-code-along.mp4 similarity index 100% rename from course/videos/13-options-code-along.mp4 rename to course/Full Algorithmic Trading Using Python/videos/13-options-code-along.mp4 diff --git a/course/videos/14-crypto-trading-bots.mp4 b/course/Full Algorithmic Trading Using Python/videos/14-crypto-trading-bots.mp4 similarity index 100% rename from course/videos/14-crypto-trading-bots.mp4 rename to course/Full Algorithmic Trading Using Python/videos/14-crypto-trading-bots.mp4 diff --git a/course/videos/15-algorithm-framework.mp4 b/course/Full Algorithmic Trading Using Python/videos/15-algorithm-framework.mp4 similarity index 100% rename from course/videos/15-algorithm-framework.mp4 rename to course/Full Algorithmic Trading Using Python/videos/15-algorithm-framework.mp4 diff --git a/course/videos/16-data-driven-research.mp4 b/course/Full Algorithmic Trading Using Python/videos/16-data-driven-research.mp4 similarity index 100% rename from course/videos/16-data-driven-research.mp4 rename to course/Full Algorithmic Trading Using Python/videos/16-data-driven-research.mp4 diff --git a/course/videos/17-bitcoin-ml-bot.mp4 b/course/Full Algorithmic Trading Using Python/videos/17-bitcoin-ml-bot.mp4 similarity index 100% rename from course/videos/17-bitcoin-ml-bot.mp4 rename to course/Full Algorithmic Trading Using Python/videos/17-bitcoin-ml-bot.mp4 diff --git a/course/videos/18-live-trading.mp4 b/course/Full Algorithmic Trading Using Python/videos/18-live-trading.mp4 similarity index 100% rename from course/videos/18-live-trading.mp4 rename to course/Full Algorithmic Trading Using Python/videos/18-live-trading.mp4 diff --git a/course/videos/19-trading-bot-50-lines.mp4 b/course/Full Algorithmic Trading Using Python/videos/19-trading-bot-50-lines.mp4 similarity index 100% rename from course/videos/19-trading-bot-50-lines.mp4 rename to course/Full Algorithmic Trading Using Python/videos/19-trading-bot-50-lines.mp4 diff --git a/course/README.md b/course/README.md index efd46e9..5054ebd 100644 --- a/course/README.md +++ b/course/README.md @@ -1,37 +1,20 @@ -# Full Algorithmic Trading Using Python — 课程教程 +# course — 量化学习课程与资料 -> 本目录是对 YouTube 频道 **TradeOptionsWithMe** 的《Full Algorithmic Trading Using Python》系列的**学习笔记 + 视频归档**。 -> 播放列表:https://youtube.com/playlist?list=PLtqRgJ_TIq8Y6YG8-G-ETIFW_36mvxMLad +本目录按「课程 + 资料 + 练习」分类归档。 -- **集数**:19 集 | **总时长**:约 6 小时 45 分 -- **每集内容**:📌 中文要点导读(提炼) + 📝 英文完整文稿(本地 ASR 转写) + 🎬 本地视频(360p) -- **提醒**:文稿由自动语音识别生成,**未人工校对**;仅供个人学习检索,版权归原作者所有。视频画质上限 360p(YouTube 未登录下载限制)。 +## 目录结构 -## 目录 +``` +course/ +├── Full Algorithmic Trading Using Python/ # 视频课程(19集,笔记+视频存档) +├── 学习资料/ # 学习资料总表 / 视频候选清单 +└── 动手练习/ # 可运行的 A 股量化练习代码 +``` -| 集 | 标题 | 时长 | 链接 | -|---|---|---|---| -| 01 | Introduction(课程总览) | 7:19 | [📄 笔记](01-introduction.md) · [🎬 视频](videos/01-introduction.mp4) | -| 02 | How Trading Algorithms Work(算法原理与开发流程) | 10:03 | [📄 笔记](02-episode-2.md) · [🎬 视频](videos/02-episode-2.mp4) | -| 03 | Key Concepts(关键概念:时间处理·骨架·Symbol) | 10:05 | [📄 笔记](03-key-concepts.md) · [🎬 视频](videos/03-key-concepts.mp4) | -| 04 | Handling Data(处理数据 · 第一个算法) | 18:01 | [📄 笔记](04-handling-data.md) · [🎬 视频](videos/04-handling-data.mp4) | -| 05 | Trading & Orders(下单、订单管理与调试) | 28:46 | [📄 笔记](05-trading-and-orders.md) · [🎬 视频](videos/05-trading-and-orders.mp4) | -| 06 | Indicators & Historical Data(指标与历史数据) | 28:32 | [📄 笔记](06-indicators-history.md) · [🎬 视频](videos/06-indicators-history.mp4) | -| 07 | Consolidators & Rolling Windows(合并器、滚动窗口、事件调度) | 22:40 | [📄 笔记](07-consolidators-rolling-windows.md) · [🎬 视频](videos/07-consolidators-rolling-windows.mp4) | -| 08 | Dynamic Universes(动态证券池与基本面选股) | 25:30 | [📄 笔记](08-dynamic-universes.md) · [🎬 视频](videos/08-dynamic-universes.mp4) | -| 09 | Twitter Trading Bot(自定义数据 · 推文情绪) | 26:52 | [📄 笔记](09-twitter-trading-bot.md) · [🎬 视频](videos/09-twitter-trading-bot.mp4) | -| 10 | Backtesting & Performance Analysis(回测与绩效评估) | 25:45 | [📄 笔记](10-backtesting-performance.md) · [🎬 视频](videos/10-backtesting-performance.mp4) | -| 11 | Forex Trading(外汇 · 均值回归) | 13:27 | [📄 笔记](11-forex-trading.md) · [🎬 视频](videos/11-forex-trading.mp4) | -| 12 | Options Trading(期权入门) | 15:28 | [📄 笔记](12-options-trading.md) · [🎬 视频](videos/12-options-trading.mp4) | -| 13 | Options Code-Along(保护性看跌期权实战) | 26:06 | [📄 笔记](13-options-code-along.md) · [🎬 视频](videos/13-options-code-along.mp4) | -| 14 | Crypto Trading Bots(加密货币 · RSI 动量) | 15:51 | [📄 笔记](14-crypto-trading-bots.md) · [🎬 视频](videos/14-crypto-trading-bots.mp4) | -| 15 | The Algorithm Framework(算法框架) | 34:14 | [📄 笔记](15-algorithm-framework.md) · [🎬 视频](videos/15-algorithm-framework.mp4) | -| 16 | Data-Driven Research(研究环境 · QuantBook) | 21:52 | [📄 笔记](16-data-driven-research.md) · [🎬 视频](videos/16-data-driven-research.mp4) | -| 17 | Bitcoin ML Bot(用神经网络做比特币) | 31:07 | [📄 笔记](17-bitcoin-ml-bot.md) · [🎬 视频](videos/17-bitcoin-ml-bot.mp4) | -| 18 | How to Live Trade(实盘部署与 Paper Trading) | 26:03 | [📄 笔记](18-live-trading.md) · [🎬 视频](videos/18-live-trading.mp4) | -| 19 | 50-Line Trading Bot(50 行代码 · 标普成分股调整) | 17:29 | [📄 笔记](19-trading-bot-50-lines.md) · [🎬 视频](videos/19-trading-bot-50-lines.mp4) | +| 分类 | 说明 | +|---|---| +| `Full Algorithmic Trading Using Python/` | YouTube「TradeOptionsWithMe」系列全套:19 集中文要点笔记 + 英文转写 + 本地视频 | +| `学习资料/` | `资料总表.md`(书单/平台/框架/社区)、`视频候选清单.md`(B站待下载候选) | +| `动手练习/` | 01 pandas热身 · 02 akshare取数 · 03 双均线回测 · 04 动量轮动 · 05 多因子;含 `lib_quant.py`、`run.sh` | -## 关于本归档 -- 视频:经 yt-dlp 下载归档(360p),讲稿:faster-whisper 本地转写,导读:小五整理。 -- 系列主线为 **Python + QuantConnect(Lean 引擎)** 开发算法交易:从概念 → 下单/指标/数据 → 各类资产(股/汇/期权/币)→ 框架/研究/ML → 实盘。 -- 生成日期:2026-09-12。 +> 整理:小五 | 2026-09-28 diff --git a/course/动手练习/01_pandas_热身.py b/course/动手练习/01_pandas_热身.py new file mode 100644 index 0000000..f14bb59 --- /dev/null +++ b/course/动手练习/01_pandas_热身.py @@ -0,0 +1,26 @@ +"""01 | pandas 热身:收益率、波动、净值曲线 +目标:搞懂量化里最基础的三个东西——收益、风险、净值。 +""" +import pandas as pd, numpy as np +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt +from lib_quant import get_daily, add_returns, net_value, stats + +df = get_daily("600519", "20200101", "20241231") # 贵州茅台 +df = add_returns(df) +nv = net_value(df["ret"]) +print("==", "600519 贵州茅台", "==") +print(df[["日期", "收盘", "ret"]].tail(3).to_string(index=False)) +print("绩效:", stats(df["ret"])) + +plt.figure(figsize=(9, 4)) +plt.plot(df["日期"], nv) +plt.title("Net value (buy & hold)") +plt.xlabel("date"); plt.ylabel("nav") +plt.tight_layout(); plt.savefig("../data/01_net_value.png", dpi=110) +print("图已存 data/01_net_value.png") + +# 思考题: +# 1) 为什么不看"价格涨了多少",而要看"收益率"和"净值"? +# 2) 日收益率为 0 的日子占多少?(df['ret'].eq(0).mean()) diff --git a/course/动手练习/02_拉数据_akshare.py b/course/动手练习/02_拉数据_akshare.py new file mode 100644 index 0000000..e9be00d --- /dev/null +++ b/course/动手练习/02_拉数据_akshare.py @@ -0,0 +1,19 @@ +"""02 | 用 akshare 拉数据并落地缓存 +目标:掌握免费 A股数据源用法——这是量化的一切起点。 +""" +from lib_quant import get_daily, CACHE +import os + +for code, name in [("000001", "平安银行"), ("600519", "贵州茅台"), ("300750", "宁德时代")]: + df = get_daily(code, "20230101", "20241231") + d0 = str(df["日期"].iloc[0])[:10] + d1 = str(df["日期"].iloc[-1])[:10] + print(f"{code} {name}: {len(df)} 行 | {d0} ~ {d1}") + print(" 列:", list(df.columns)) + +print("\n缓存目录:", os.path.abspath(CACHE)) +print("文件:", sorted(os.listdir(CACHE))) + +# 思考题: +# 1) 前复权(qfq)/后复权(hfq)/不复权 区别?算收益率该用哪个?(改 adjust 参数对比) +# 2) 每日数据延迟多久?实盘能用吗?(提示: akshare 文档 + 交易所规则) diff --git a/course/动手练习/03_双均线回测.py b/course/动手练习/03_双均线回测.py new file mode 100644 index 0000000..0dc5d1e --- /dev/null +++ b/course/动手练习/03_双均线回测.py @@ -0,0 +1,33 @@ +"""03 | 双均线策略 + 回测 +目标:写出人生第一个完整策略,并做归因。 +策略:5日均线上穿20日均线买入,下穿卖出。 +""" +import pandas as pd, numpy as np +import matplotlib; matplotlib.use("Agg") +import matplotlib.pyplot as plt +from lib_quant import get_daily, add_returns, net_value, stats + +FAST, SLOW = 5, 20 +df = get_daily("600519", "20200101", "20241231") +df = add_returns(df) +df["ma_fast"] = df["收盘"].rolling(FAST).mean() +df["ma_slow"] = df["收盘"].rolling(SLOW).mean() +df["signal"] = (df["ma_fast"] > df["ma_slow"]).astype(int) # 1=持有 0=空仓 +df["pos"] = df["signal"].shift(1).fillna(0) # 次日开盘才算,防未来函数 +df["strat_ret"] = df["pos"] * df["ret"] + +nv_bh, nv_st = net_value(df["ret"]), net_value(df["strat_ret"]) +print("== 买入持有 ==", stats(df["ret"])) +print("== 双均线 ==", stats(df["strat_ret"])) + +plt.figure(figsize=(10, 4)) +plt.plot(df["日期"], nv_bh, label="BuyHold") +plt.plot(df["日期"], nv_st, label=f"MA{FAST}/{SLOW}") +plt.legend(); plt.title("Strategy vs Buy&Hold"); plt.tight_layout() +plt.savefig("../data/03_dual_ma.png", dpi=110) +print("图已存 data/03_dual_ma.png") + +# 思考题: +# 1) 为什么 pos 要 shift(1)?不 shift 会怎样?(把 shift(1) 去掉对比——这叫"未来函数") +# 2) 改 FAST/SLOW 参数,结果稳吗?换 (10,60) 试试——这叫参数敏感性 +# 3) 这策略赢过买入持有了吗?为什么? diff --git a/course/动手练习/04_动量轮动.py b/course/动手练习/04_动量轮动.py new file mode 100644 index 0000000..41c30e9 --- /dev/null +++ b/course/动手练习/04_动量轮动.py @@ -0,0 +1,36 @@ +"""04 | 动量轮动策略 +目标:从"单票择时"升级到"多标的轮动"。 +策略:每月末看过去 N 日涨幅,持有最强的一只。 +""" +import pandas as pd, numpy as np +from lib_quant import get_daily, net_value, stats + +POOL = {"600519": "贵州茅台", "000001": "平安银行", "300750": "宁德时代", + "601318": "中国平安", "000858": "五粮液"} +LOOKBACK, FREQ = 20, 20 # 回看20日,每20个交易日调仓 + +px = {} +for c in POOL: + d = get_daily(c, "20200101", "20241231")[["日期", "收盘"]].set_index("日期") + px[c] = d["收盘"] +prices = pd.DataFrame(px).dropna() +mom = prices.pct_change(LOOKBACK) + +rets = [] +cur = None +for i in range(LOOKBACK, len(prices) - 1): + if (i - LOOKBACK) % FREQ == 0: # 调仓日 + cur = mom.iloc[i].idxmax() # 动量最强 + if cur is not None: + r = prices[cur].iloc[i + 1] / prices[cur].iloc[i] - 1 + rets.append(r) + else: + rets.append(0.0) + +s = pd.Series(rets) +print("== 动量轮动 ==", stats(s)) +print("== 等权买入持有 ==", stats(prices.pct_change().mean(axis=1).iloc[LOOKBACK:])) + +# 思考题: +# 1) 换 LOOKBACK (10/60/120) 看结果——动量在A股有效吗? +# 2) 为什么不持有全部、按动量加权?(提示: 集中 vs 分散) diff --git a/course/动手练习/05_多因子选股.py b/course/动手练习/05_多因子选股.py new file mode 100644 index 0000000..bac3442 --- /dev/null +++ b/course/动手练习/05_多因子选股.py @@ -0,0 +1,37 @@ +"""05 | 多因子选股(横截面) +目标:体验"因子"最朴素的样子——按指标排序选股。 +数据:akshare 全A快照(含市盈率/市净率等)。 +""" +import time +import akshare as ak, pandas as pd + +def fetch_spot(retries=6): + last = None + for i in range(retries): + try: + return ak.stock_zh_a_spot_em() + except Exception as e: + last = e; time.sleep(3 + i * 3) + raise last + +try: + spot = fetch_spot() + print("全A快照:", spot.shape) + df = spot.copy() + pe = pd.to_numeric(df.get("市盈率-动态"), errors="coerce") + df = df[pe.notna()].copy() + df["EP"] = 1 / pe[pe.notna()] # 盈利收益率(1/PE) + df["EP_rank"] = df["EP"].rank(pct=True) + top = df.sort_values("EP_rank", ascending=False).head(20)[ + ["代码", "名称", "最新价", "市盈率-动态", "EP_rank"]] + print("\n== 按盈利收益率(EP)选出的前20(低估值)==") + print(top.to_string(index=False)) + top.to_csv("../data/05_top20_EP.csv", index=False, encoding="utf-8-sig") + print("已存 data/05_top20_EP.csv") +except Exception as e: + print("取数失败(网络/接口变动):", repr(e)[:200]) + print("可稍后重跑;或先跑 01-04(已缓存,离线可跑)") + +# 思考题: +# 1) 单因子排序选股有什么坑?(行业偏差/市值偏差/未来函数) +# 2) 怎么把2个因子合成打分?(标准化后加权,试试 z-score) diff --git a/course/动手练习/README.md b/course/动手练习/README.md new file mode 100644 index 0000000..17cb687 --- /dev/null +++ b/course/动手练习/README.md @@ -0,0 +1,23 @@ +# 量化动手练习(用真实 A 股数据) + +> 目标:把"看书看不进去"的瓶颈,换成**能跑出结果**的闭环练习。 +> 环境:Python 3.11 + pandas/akshare/backtrader/matplotlib(已装在 `../pylibs`) +> 运行:`bash run.sh`(全部)或 `bash run.sh 03`(单课) + +## 怎么用 +每一课 = 目标 + 代码 + 思考题。先跑通,再改参数看结果变化,最后回答思考题。卡住直接问小五。 + +## 课程表 +| 课 | 文件 | 主题 | 你会学到 | +|---|---|---|---| +| 01 | 01_pandas_热身.py | 收益率/波动/净值 | 量化最基础的语言 | +| 02 | 02_拉数据_akshare.py | 用 akshare 拉 A股数据 | 免费数据源怎么用 | +| 03 | 03_双均线回测.py | 双均线策略+回测 | 一个完整策略长什么样 | +| 04 | 04_动量轮动.py | 动量轮动策略 | 多标的轮动调仓 | +| 05 | 05_多因子选股.py | 多因子选股 | 从横截面数据里选股 | + +## 数据 +- 默认用 akshare 在线拉(国内可达),首次拉完自动缓存到 `../data/cache/*.csv` + +## 学习闭环 +跑通 → 改参数 → 想为什么 → 写结论 → 告诉小五批改/加题 diff --git a/course/动手练习/lib_quant.py b/course/动手练习/lib_quant.py new file mode 100644 index 0000000..614560d --- /dev/null +++ b/course/动手练习/lib_quant.py @@ -0,0 +1,48 @@ +"""量化练习公共库:数据获取(带缓存+重试) + 常用指标 + 回测指标。""" +import os, time, pandas as pd, numpy as np + +CACHE = os.path.join(os.path.dirname(__file__), "..", "data", "cache") +os.makedirs(CACHE, exist_ok=True) + +def _fetch(symbol, start, end, adjust, retries=6, wait=2.0): + import akshare as ak + last = None + for i in range(retries): + try: + return ak.stock_zh_a_hist(symbol=symbol, period="daily", + start_date=start, end_date=end, adjust=adjust) + except Exception as e: # 网络间歇性抽风,重试 + last = e + time.sleep(wait * (i + 1)) + raise last + +def get_daily(symbol="000001", start="20200101", end="20241231", adjust="qfq"): + """拉单只A股日线(前复权),带本地缓存与自动重试。""" + f = os.path.join(CACHE, f"{symbol}_{start}_{end}_{adjust}.csv") + if os.path.exists(f): + return pd.read_csv(f, parse_dates=["日期"]) + df = _fetch(symbol, start, end, adjust) + df.to_csv(f, index=False, encoding="utf-8-sig") + return df + +def add_returns(df, price_col="收盘"): + df = df.copy() + df["ret"] = df[price_col].pct_change().fillna(0.0) + return df + +def net_value(ret): + return (1 + pd.Series(ret).fillna(0.0)).cumprod() + +def stats(ret, periods=252): + ret = pd.Series(ret).fillna(0.0) + nv = net_value(ret); total = nv.iloc[-1] - 1 + ann = (1 + total) ** (periods / max(len(ret), 1)) - 1 + vol = ret.std() * np.sqrt(periods) + sharpe = (ret.mean() * periods) / vol if vol > 0 else np.nan + dd = (nv / nv.cummax() - 1).min() + calmar = ann / abs(dd) if dd < 0 else np.nan + return {"总收益": f"{total:.2%}", "年化": f"{ann:.2%}", "年化波动": f"{vol:.2%}", + "夏普": f"{sharpe:.2f}", "最大回撤": f"{dd:.2%}", "卡玛": f"{calmar:.2f}"} + +def max_drawdown(nv): + return (nv / nv.cummax() - 1).min() diff --git a/course/动手练习/run.sh b/course/动手练习/run.sh new file mode 100644 index 0000000..7a6bdb1 --- /dev/null +++ b/course/动手练习/run.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# 一键跑练习:bash run.sh 或 bash run.sh 03 +cd "$(dirname "$0")" +export PYTHONPATH="$(pwd)/../pylibs" +export MPLCONFIGDIR="/tmp/mpl" +mkdir -p ../data/cache +case "$1" in + 01|02|03|04|05) python3 ${1}_*.py ;; + *) for f in 0*.py; do echo; echo "############ $f ############"; python3 "$f"; done ;; +esac diff --git a/course/动手练习/seed_cache.py b/course/动手练习/seed_cache.py new file mode 100644 index 0000000..b729b9f --- /dev/null +++ b/course/动手练习/seed_cache.py @@ -0,0 +1,23 @@ +"""预热缓存:把练习需要的数据一次性拉齐(带重试+间隔)。之后离线可跑。""" +import time, sys +from lib_quant import get_daily, CACHE +JOBS = [ + ("600519","20200101","20241231"), ("600519","20230101","20241231"), + ("000001","20200101","20241231"), ("000001","20230101","20241231"), + ("300750","20200101","20241231"), ("300750","20230101","20241231"), + ("601318","20200101","20241231"), ("000858","20200101","20241231"), +] +for sym,s,e in JOBS: + import os + f=os.path.join(CACHE,f"{sym}_{s}_{e}_qfq.csv") + if os.path.exists(f): + print("cached", sym, s); continue + for att in range(8): + try: + df=get_daily(sym,s,e); print("OK", sym, s, len(df)); break + except Exception as ex: + print("retry",sym,att,repr(ex)[:60]); time.sleep(5+att*3) + else: + print("FAIL", sym, s); sys.exit(1) + time.sleep(3) +print("ALL DONE") diff --git a/course/学习资料/视频候选清单.md b/course/学习资料/视频候选清单.md new file mode 100644 index 0000000..981301a --- /dev/null +++ b/course/学习资料/视频候选清单.md @@ -0,0 +1,38 @@ +# 视频候选清单(确认后再下载) + +> 整理:小五 | 2026-09-28 | 来源:B站搜索实测(github/google 不通,走搜狗+必应国内) +> 状态:**仅候选,未下载**。你勾选后我用 BBDown / yt-dlp 下到本地。 + +## 一、推荐下载(值回票价) + +| # | 名称 | UP主 | 链接 | 类型 | 说明 | +|---|---|---|---|---|---| +| 1 | WorldQuant Brain《零基础学量化》AI版 第一课 | 水木人中 | https://www.bilibili.com/video/BV1d3oFBPES6 | 系统课 | 零基础成体系,从0讲策略 | +| 2 | 《因子投资-方法与实践》石川 第1章 因子投资基础 | 量衍金工 | https://www.bilibili.com/video/BV1VxZcBqEsj | 读书课 | **石川《因子投资》**配套讲解,进阶重点 | +| 3 | 《多因子策略实战》构建量化选股模型 | (投资经典精读) | https://www.bilibili.com/video/BV118at6ME3g | 读书课 | 多因子选股实战思路 | +| 4 | 新手怎么开始学量化?认知篇:何为量化 | 龙猫说财 | https://www.bilibili.com/video/BV1Vtht62EPY | 入门 | 建立正确认知,避坑 | +| 5 | 普通人如何从0开始做量化?(保姆级全流程) | QuantX西蒙斯 | https://www.bilibili.com/video/BV1JY8F61E6y | 入门 | 全流程走一遍 | +| 6 | 5天学会 PTrade - AI协助策略 | 国金证券宜宾营业部 | https://www.bilibili.com/video/BV1aekKBkEVK | 券商课 | 券商官方,实盘环境入门 | +| 7 | 怎样用 Deepseek Harness 做量化策略研究 | Mr看海 | https://www.bilibili.com/video/BV1Nzb367E5J | AI+量化 | 用LLM做研究,前沿 | +| 8 | 【2026最新】Codex 量化实战教学 | 搞AI的阿黑 | https://www.bilibili.com/video/BV1jgtZ6fEHq | AI+量化 | 编程Agent做量化 | + +## 二、可作补充(先看一/再决定) + +| 名称 | UP主 | 链接 | 说明 | +|---|---|---|---| +| 横测:做量化最好用的大模型 | frank-quant | https://www.bilibili.com/video/BV1ijYB6QE1Y | 工具选型参考 | +| 量化投资邢不行(系列) | 量化投资邢不行啊 | https://www.bilibili.com/video/BV1RZfxB1E68 | 拆解网红指标,防坑 | +| 爆火Jev接入量化实盘实测 | 发明者量化 | https://www.bilibili.com/video/BV1kRez6BEuq | 实盘+AI | + +## 三、非B站课程(文本/视频混合) +- 慕课网 / 网易云课堂:搜「Python 量化投资」— 有系统付费课 +- 中国大学 MOOC:高校《金融工程》《量化投资》公开课(免费) + +## 四、不推荐(已排除) +- 币圈量化、跟单订阅、QMT连板超短、"永久躺平收益"类 —— 多为广告/割韭菜,已剔除 + +## 五、下载方案(确认后执行) +- 工具:**BBDown**(B站专用,支持 1080P/4K、字幕、合集)+ **yt-dlp**(通用) +- 输出:`量化学习/data/videos/`,可合并音频+视频、下字幕 +- ⚠️ 付费/会员课程需自备账号;我这边无账号只能下免费公开视频 +- 需要的话我可以顺带**提取字幕**,转成文本给你看(更符合你的文本偏好) diff --git a/course/学习资料/资料总表.md b/course/学习资料/资料总表.md new file mode 100644 index 0000000..c20517f --- /dev/null +++ b/course/学习资料/资料总表.md @@ -0,0 +1,53 @@ +# 量化投资学习资料总表(适合国内环境) + +> 汇总:小五 | 2026-09-28 +> 来源:小五主搜 + 小强(Gitea #31) + 小马(Gitea #30)(后者回帖后并入本表) +> 说明:沙箱内 github/google 不通,链接优先给**国内可访问**的;GitHub 项目给 gitee 镜像路径。 + +## A. 书单(文本 · 打地基) + +| 书名 | 作者 | 阶段 | 国内可购 | 备注 | +|---|---|---|---|---| +| 《打开量化投资的黑箱》第2版 | Rishi Narang | 入门 | ✅ 中文版 | 建立行业全貌,第一本 | +| 《量化交易:如何建立自己的算法交易事业》 | Ernest Chan | 入门→实战 | ✅ 中文版 | 从0讲起,可照做 | +| 《算法交易:制胜策略与原理》 | Ernest Chan | 进阶 | ✅ | 上本续作 | +| 《Systematic Trading》 | Robert Carver | 进阶 | 英文为主 | 风险预算/系统化思想 | +| 《主动投资组合管理》 | Grinold & Kahn | 进阶 | ✅ 中文版 | 因子/风险模型天花板 | +| 《量化投资:策略与技术》 | 丁鹏 | 入门→进阶 | ✅ | 国内教材,A股语境 | +| 《Python金融大数据分析》 | Yves Hilpisch | 工具 | ✅ | 配合实战 | +| 《海龟交易法则》 | Curtis Faith | 入门 | ✅ | 趋势跟踪思想 | +| 《统计套利》 | Andrew Pole | 进阶 | ✅ | 配对/均值回归 | + +## B. 在线平台 / 开源框架(文本为主 · 国内可访问) + +| 名称 | 类型 | 链接 | 阶段 | 备注 | +|---|---|---|---|---| +| 聚宽 JoinQuant | 在线研究+回测+社区 | https://www.joinquant.com | 全阶段 | **最省事入口**,A股数据全、策略帖海量 | +| 米筐 RiceQuant | 在线平台 | https://www.ricequant.com | 全阶段 | 同类 | +| 掘金量化 | 在线平台 | https://www.myquant.cn | 全阶段 | 同类 | +| BigQuant | 在线AI量化 | https://bigquant.com | 进阶 | 机器学习向 | +| AKShare | 免费数据源(库) | https://akshare.akfamily.xyz | 数据 | ✅ 中文文档,A股/期货/基金 | +| Tushare | 数据源(库) | https://tushare.pro | 数据 | 需注册积分 | +| backtrader | 回测框架 | 文档 https://www.backtrader.com (中文教程多) | 回测 | 轻量易上手 | +| vnpy | 交易框架 | https://www.vnpy.com | 实盘 | 国内最主流,配书《vn.py 从入门到进阶》 | +| Qlib(微软) | AI量化投研 | github.com/microsoft/qlib(用 gitee 镜像) | 进阶/ML | 因子+模型全流程 | + +## C. 社区 / 专栏(文本) + +| 名称 | 链接 | 备注 | +|---|---|---| +| 知乎「量化投资学习路线图·书籍篇」等专栏 | https://zhuanlan.zhihu.com | 路线梳理 | +| CSDN 量化专栏 | https://blog.csdn.net | 中文实战多 | +| 掘金 | https://juejin.cn | 工程向 | +| 聚宽/米筐社区帖 | 平台内 | 策略源码 | + +## D. 视频(候选见「视频候选清单.md」,确认后再下载) + +## E. 按阶段的路线(建议照走) +1. **基础**:Python + pandas/numpy + 金融常识 + 统计学 +2. **数据+回测**:AKShare/Tushare + 聚宽/backtrader → 写双均线、动量 +3. **策略进阶**:多因子、统计套利、CTA、事件驱动 +4. **工程/ML**:Qlib、因子库、ML选股、风控 +5. **实盘**:vnpy 接券商/期货 + +> 待办:小强(#31)、小马(#30) 回帖后并入本表并去重。