66 lines
2.0 KiB
Python
66 lines
2.0 KiB
Python
|
import glob
|
||
|
import pandas as pd
|
||
|
|
||
|
from plotting import BacktestChart, plot
|
||
|
|
||
|
DATE = 'Period'
|
||
|
PROFIT = 'Cum. net profit'
|
||
|
TOTAL_PROFIT = 'Total Cum. net profit'
|
||
|
|
||
|
backtest_results_path = ''
|
||
|
backtest_result_plot_title = ''
|
||
|
|
||
|
all_start_dates = []
|
||
|
all_end_dates = []
|
||
|
|
||
|
# Find the earliest start date and the latest end date among all backtests.
|
||
|
for file in glob.glob(backtest_results_path):
|
||
|
backtest = pd.read_csv(file, sep = ',', usecols = [DATE])
|
||
|
backtest[DATE] = pd.to_datetime(backtest[DATE])
|
||
|
all_start_dates.append(backtest[DATE].min())
|
||
|
all_end_dates.append(backtest[DATE].max())
|
||
|
|
||
|
start_date = min(all_start_dates)
|
||
|
end_date = max(all_end_dates)
|
||
|
all_dates = pd.date_range(start = start_date, end = end_date, freq = 'D')
|
||
|
|
||
|
backtests = []
|
||
|
|
||
|
def parse_profit(profit):
|
||
|
profit = profit.replace('$', '').replace(',', '').strip()
|
||
|
# Negative values are enclosed in parentheses.
|
||
|
if profit.startswith('(') and profit.endswith(')'):
|
||
|
profit = profit.strip('()')
|
||
|
return -float(profit)
|
||
|
else:
|
||
|
return float(profit)
|
||
|
|
||
|
for file in glob.glob(backtest_results_path):
|
||
|
backtest = pd.read_csv(file, sep = ',')
|
||
|
|
||
|
backtest[DATE] = pd.to_datetime(backtest[DATE])
|
||
|
backtest.set_index(DATE, inplace = True)
|
||
|
|
||
|
backtest[PROFIT] = backtest[PROFIT].apply(parse_profit)
|
||
|
backtest = backtest[[PROFIT]]
|
||
|
|
||
|
backtest = backtest.reindex(all_dates)
|
||
|
backtests.append(backtest)
|
||
|
|
||
|
combined_backtests = pd.concat(backtests, axis = 1)
|
||
|
|
||
|
combined_backtests.dropna(axis = 0, how = 'all', inplace = True)
|
||
|
combined_backtests.fillna(method = 'ffill', inplace = True)
|
||
|
combined_backtests.fillna(0, inplace = True)
|
||
|
|
||
|
combined_backtests[TOTAL_PROFIT] = combined_backtests.sum(axis = 1)
|
||
|
|
||
|
combined_backtests = combined_backtests[[TOTAL_PROFIT]]
|
||
|
combined_backtests.reset_index(inplace = True)
|
||
|
combined_backtests.rename(columns={'index': 'Date'}, inplace = True)
|
||
|
|
||
|
plot(BacktestChart(
|
||
|
dates = combined_backtests['Date'],
|
||
|
profit = combined_backtests[TOTAL_PROFIT],
|
||
|
title = backtest_result_plot_title
|
||
|
))
|