python使用pandas進行量化回測
更新時間:2022年03月24日 15:41:09 作者:神出鬼沒,指的就是我!
這篇文章主要介紹了python使用pandas進行量化回測,文章圍繞pandas進行量化回測的相關資料展開簡單內(nèi)容,文章內(nèi)容可以做一些比較簡單的技術指標測試,需要的朋友可以參考一下
下面文章描述可能比excel高級一點,距離backtrader這些框架又差一點。做最基礎的測試可以,如果后期加入加倉功能,或者是止盈止損等功能,很不合適。只能做最簡單的技術指標測試。
導包,常用包導入:
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ù)為對象分析:
bond_zh_hs_daily_df = ak.bond_zh_hs_daily(symbol="sh010107")
添加指標:
def backtest_trend_strategy(ohlc: pd.DataFrame, ? ? ? ? ? ? ? ? ? ? ? ? ? ? fast_period: int = 50, ? ? ? ? ? ? ? ? ? ? ? ? ? ? slow_period: int = 200, ? ? ? ? ? ? ? ? ? ? ? ? ? ? threshold: float = 1.0) -> pd.DataFrame: ? ? """封裝向量化回測的邏輯""" ? ? # 計算指標 ? ? 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 ? ? ? # 生成信號,1表示做多,-1表示做空,0表示空倉 ? ? ohlc["signal"] = np.where(ohlc["pct_diff"] > threshold, 1, 0) ? ? ohlc["signal"] = np.where(ohlc["pct_diff"] < -threshold, -1, ohlc["signal"]) ? ? ? # 計算策略收益率 ? ? 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
運行策略,并繪制圖片:
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])
? ??
?
# 散點圖:策略收益率 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(%)")到此這篇關于python使用pandas進行量化回測的文章就介紹到這了,更多相關pandas進行量化回測內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python壓縮模塊zipfile實現(xiàn)原理及用法解析
這篇文章主要介紹了Python壓縮模塊zipfile實現(xiàn)原理及用法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-08-08

