Otama's Playground > 投資 > Backtraderを使った簡単バックテスト:Buy and Hold戦略編

Backtraderを使った簡単バックテスト:Buy and Hold戦略編

Backtraderは、Pythonでのバックテストを容易にする強力なライブラリです。本記事では、Buy and Hold戦略を実装し、過去10年間のデータを使用してバックテストを行う方法を簡単に説明します。

1. 環境準備

ライブラリのインストール

Python
# install requirement
%pip install backtrader yfinance matplotlib

2. ライブラリのインポート

必要なライブラリをインポートします

Python
# import libs
import datetime
import backtrader as bt
import yfinance as yf
import matplotlib.pyplot as plt

3. パラメータ設定

必要なパラメータを設定します。

Python
## tickerと割合
TICKERS = {"VTI": 0.4, "BND": 0.4, "GLD": 0.2}
## 開始日時と終了日時
FROMDATE = datetime.datetime(2014, 7, 1)
TODATE = datetime.datetime(2024, 7, 1)

4. Strategyを実装する

Strategy – Backtrader

Python
# Buy and Hold戦略の定義
class BuyAndHold(bt.Strategy):
def __init__(self):
pass
def next(self):
if not self.position:
for data in self.datas:
allocation= data.target
cash_for_asset = self.broker.get_cash() * allocation
self.buy(data=data, size=int(cash_for_asset // data.close[0]))

5. バックテストを実行する

データの読みこみを行い、バックテストを実行します。

Python
# backtraderの初期化
cerebro = bt.Cerebro()
cerebro.broker.set_cash(10000)
cerebro.addstrategy(BuyAndHold)
# yahoofinanceからデータを読み込む
for ticker, target in TICKERS.items():
data = bt.feeds.PandasData(
dataname=yf.download(ticker, start=FROMDATE, end=TODATE)
)
data.target = target
cerebro.adddata(data, name=ticker)
# バックテストの実行
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

実行結果

Starting Portfolio Value: 10000.00
Final Portfolio Value: 17274.97

6. バックテストの結果を可視化

backtraderに組み込みの可視化関数があるためそれを実行します。最初のみbuyが行われていることが読み取れます。

Plotting – Backtrader

Python
plt.rcParams['figure.figsize'] = [12, 10]
cerebro.plot()
Buy&Holdのバックテスト結果

返信を残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です