python使用pandas進(jìn)行量化回測(cè)
下面文章描述可能比excel
高級(jí)一點(diǎn),距離backtrader
這些框架又差一點(diǎn)。做最基礎(chǔ)的測(cè)試可以,如果后期加入加倉(cāng)功能,或者是止盈止損等功能,很不合適。只能做最簡(jiǎn)單的技術(shù)指標(biāo)測(cè)試。
導(dǎo)包,常用包導(dǎo)入:
import os import akshare as ak import requests import numpy as np import pandas as pd import matplotlib.pyplot as plt import talib as ta %matplotlib inline plt.style.use("ggplot")
獲取數(shù)據(jù),本文使用akshare中債券數(shù)據(jù)為對(duì)象分析:
bond_zh_hs_daily_df = ak.bond_zh_hs_daily(symbol="sh010107")
添加指標(biāo):
def backtest_trend_strategy(ohlc: pd.DataFrame, ? ? ? ? ? ? ? ? ? ? ? ? ? ? fast_period: int = 50, ? ? ? ? ? ? ? ? ? ? ? ? ? ? slow_period: int = 200, ? ? ? ? ? ? ? ? ? ? ? ? ? ? threshold: float = 1.0) -> pd.DataFrame: ? ? """封裝向量化回測(cè)的邏輯""" ? ? # 計(jì)算指標(biāo) ? ? ohlc["fast_ema"] = talib.EMA(ohlc.close, fast_period) ? ? ohlc["slow_ema"] = talib.EMA(ohlc.close, slow_period) ? ? ohlc["pct_diff"] = (ohlc["fast_ema"] / ohlc["slow_ema"] - 1) * 100 ? ? ? # 生成信號(hào),1表示做多,-1表示做空,0表示空倉(cāng) ? ? ohlc["signal"] = np.where(ohlc["pct_diff"] > threshold, 1, 0) ? ? ohlc["signal"] = np.where(ohlc["pct_diff"] < -threshold, -1, ohlc["signal"]) ? ? ? # 計(jì)算策略收益率 ? ? ohlc["returns"] = np.log(ohlc["close"] / ohlc["close"].shift(1)) ? ? ohlc["strategy"] = ohlc["signal"].shift(1) * ohlc["returns"] ? ? ohlc["strategy_returns"] = ohlc["strategy"].cumsum() ? ?? ? ? return ohlc
運(yùn)行策略,并繪制圖片:
data = strategy1(data) ? ? fig, ax = plt.subplots(nrows=3, ncols=1, figsize=(12, 15), sharex=True) ? ax[0].plot(data.index, data["close"]) ax[0].plot(data.index, data["fast_ema"]) ax[0].plot(data.index, data["slow_ema"]) ax[0].set_title("Price and Indicators") ? ax[1].plot(data.index, data["signal"]) ax[1].set_title("Strategy Position") ? data[["returns", "strategy"]].cumsum().plot(ax=ax[2], title="Strategy Return")
參數(shù)優(yōu)化:
# 選擇核心參數(shù)和掃描區(qū)間,其它參數(shù)保持不變 fast_period_rng = np.arange(5, 101, 5) ? total_return = [] for fast_period in fast_period_rng: ? ? ohlc = data.filter(["open", "high", "low", "close"]) ? ? res = backtest_trend_strategy(ohlc, fast_period, 200, 1.0) ? ? total_return.append(res["strategy_returns"].iloc[-1]) ? ?? ? # 散點(diǎn)圖:策略收益率 vs 快速均線回溯期 fig, ax = plt.subplots(figsize=(12, 7)) ax.plot(fast_period_rng, total_return, "r-o", markersize=10) ax.set_title("Strategy Return vs Fast period") ax.set_xlabel("fast_period") ax.set_ylabel("return(%)")
到此這篇關(guān)于python使用pandas進(jìn)行量化回測(cè)的文章就介紹到這了,更多相關(guān)pandas進(jìn)行量化回測(cè)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何利用Python實(shí)現(xiàn)一個(gè)論文降重工具
文章去重(或叫網(wǎng)頁(yè)去重)是根據(jù)文章(或網(wǎng)頁(yè))的文字內(nèi)容來(lái)判斷多個(gè)文章之間是否重復(fù),下面這篇文章主要給大家介紹了關(guān)于利用Python實(shí)現(xiàn)論文降重工具的相關(guān)資料,需要的朋友可以參考下2021-07-07python中使用smtplib和email模塊發(fā)送郵件實(shí)例
python腳本發(fā)郵件,一般會(huì)用到smtplib和email這兩個(gè)模塊??纯丛撃K怎么使用,先看smtplib模塊。 smtplib模塊定義了一個(gè)簡(jiǎn)單的SMTP客戶端,可以用來(lái)在互聯(lián)網(wǎng)上發(fā)送郵件2014-04-04Python單元測(cè)試及unittest框架用法實(shí)例解析
這篇文章主要介紹了Python單元測(cè)試及unittest框架用法實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07kaggle數(shù)據(jù)分析家庭電力消耗過(guò)程詳解
這篇文章主要為大家介紹了kaggle數(shù)據(jù)分析家庭電力消耗示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12Python實(shí)現(xiàn)的個(gè)人所得稅計(jì)算器示例
這篇文章主要介紹了Python實(shí)現(xiàn)的個(gè)人所得稅計(jì)算器,涉及Python條件判斷與數(shù)值運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2018-06-06安裝Python后IDA中找不到Python模塊的問(wèn)題解決
有天在一臺(tái)新PC上安裝完IDA和Python之后,啟動(dòng)IDA報(bào)找不到Python模塊的問(wèn)題,本文就詳細(xì)的介紹一下解決方法,感興趣的可以了解一下2021-10-10django框架實(shí)現(xiàn)模板中獲取request 的各種信息示例
這篇文章主要介紹了django框架實(shí)現(xiàn)模板中獲取request 的各種信息,結(jié)合實(shí)例形式分析了Django框架模板直接獲取request信息的相關(guān)配置與操作技巧,需要的朋友可以參考下2019-07-07Numpy數(shù)組轉(zhuǎn)置的兩種實(shí)現(xiàn)方法
下面小編就為大家分享一篇Numpy數(shù)組轉(zhuǎn)置的兩種實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04