Last active
December 27, 2025 15:44
-
-
Save ChadThackray/5048e957487ae18cc54a0db6bed033b9 to your computer and use it in GitHub Desktop.
Backtest Your Dollar Cost Average Strategy easily in Python
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
| # Licensed under the MIT License. See comment below for full licence information. | |
| import pandas as pd | |
| from backtesting import Backtest, Strategy | |
| from backtesting.test import GOOG | |
| import math | |
| class DCA(Strategy): | |
| amount_to_invest = 10 | |
| def init(self): | |
| self.day_of_week = self.I( | |
| lambda x: x, | |
| self.data.Close.s.index.dayofweek, | |
| plot = False, | |
| ) | |
| def next(self): | |
| if self.day_of_week[-1] == 1: | |
| self.buy( size = math.floor(self.amount_to_invest / self.data.Close[-1])) | |
| try: | |
| if self.data.Close[-1]/self.data.Close[-30] < 0.95: | |
| self.buy( size = math.floor(self.amount_to_invest / self.data.Close[-1])) | |
| except: | |
| pass | |
| print(GOOG) | |
| GOOG = GOOG * 10**-6 | |
| bt = Backtest( | |
| GOOG, | |
| DCA, | |
| trade_on_close = True, | |
| finalize_trades = True, | |
| ) | |
| stats = bt.run() | |
| print(stats) | |
| # Size EntryBar ExitBar EntryPrice ExitPrice | |
| trades = stats["_trades"] | |
| price_paid = trades["Size"] * trades["EntryPrice"] | |
| total_invested = price_paid.sum() | |
| current_shares = trades["Size"].sum() | |
| current_equity = current_shares * GOOG.Close.iloc[-1] | |
| print("Total investment:",total_invested) | |
| print("Current Shares:",current_shares / (10**6)) | |
| print("current Equity:", current_equity) | |
| print("Return:", current_equity / total_invested) | |
Author
@marc260870-byte. Hey Mark, yes looks like there was an API change introduced in version 0.6.0 I've updated the script like you suggested. Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Chad,
I had to insert
finalize_trades = True,before line 42 in your code, otherwise it just shows 0 trades in the stats and also subsequent calcs fail.
Maybe this is because of a newer version of the backtesting library!?
Cheers, Marc