-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathma-method-backtest.py
172 lines (138 loc) · 5.77 KB
/
ma-method-backtest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import logging
from datetime import datetime, date
from bcb import sgs
import yfinance as yf
import pandas_ta as ta
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import mplcursors
#
# Overview
#
print('\n#----------------------------- Program Overview -----------------------------#\n')
print('The models reinvest the entirety of the hypothetical value on the first day of each month based on metrics from the previous month(s).')
print('- CDI (Certificado de Depósito Interbancário): CDI is an important interest rate benchmark in Brazil.')
print('- IBOV (Ibovespa): IBOV is the benchmark stock index of the São Paulo Stock Exchange (B3).')
print('- Moving Average Method: Invests in IBOV if the previous month\'s closing value was higher than the moving average. In CDI if not.')
print('\n#----------------------------------------------------------------------------#\n')
#
# Inputs
#
# Set the logging level for yfinance to CRITICAL to reduce noise
logging.getLogger('yfinance').setLevel(logging.CRITICAL)
def validate_date(input_date):
try:
# Check if the input matches the desired format (YYYY-MM-DD)
parsed_date = datetime.strptime(input_date, '%Y-%m-%d')
year, month, day = map(str, input_date.split('-'))
if len(year) == 4 and len(month) == 2 and len(day) == 2:
if parsed_date.date() < date.today():
return True
else:
print('The start date should be before today\'s date.')
return False
else:
return False
except:
return False
def validate_ma(input_ma):
try:
ma = int(input_ma)
if ma > 0:
return True
except:
return False
start_date = None
while start_date is None:
start_date = input('Please input the analysis start date (YYYY-MM-DD): ')
if not validate_date(start_date):
print('Invalid date. Please use YYYY-MM-DD format.')
start_date = None
ma_months = None
while ma_months is None:
ma_months = input('Specify the number of months for the moving average: ')
if validate_ma(ma_months):
ma_months = int(ma_months)
else:
print('Invalid input. Please enter a positive integer for the moving average.')
ma_months = None
#
# CDI
#
# Fetch historical CDI data
cdi_data = sgs.get({'CDI': 11}, start=start_date)
cdi_data = cdi_data['CDI']
# Convert CDI rates to decimal form (dividing by 100)
cdi_daily_returns = cdi_data / 100
cdi_cumulative_daily_returns = (1 + cdi_daily_returns).cumprod()
cdi_month_closing = cdi_cumulative_daily_returns.resample('ME').last()
cdi_returns = cdi_cumulative_daily_returns.resample('ME').last().pct_change().dropna()
# Calculate returns for the first month (missing with the previous method)
cdi_month_opening = cdi_cumulative_daily_returns.resample('ME').first()
first_month_cdi_returns = (cdi_month_closing.iloc[0] - cdi_month_opening.iloc[0]) / cdi_month_opening.iloc[0]
#
# IBOV
#
# Download historical data for the Bovespa index (^BVSP)
ibov_data = yf.download('^BVSP', start=start_date)
ibov = ibov_data['Adj Close']
# Calculate moving averages
ibov_ma = ta.sma(ibov_data['Close'], ma_months * 21) # Average of 21 working days / month
# Convert the index to datetime and sort the data by date in ascending order for all DataFrames
ibov.index = pd.to_datetime(ibov.index)
ibov = ibov.sort_index(ascending=True)
ibov_ma.index = pd.to_datetime(ibov_ma.index)
ibov_ma = ibov_ma.sort_index(ascending=True)
ibov_month_closing = ibov.resample('ME').last()
ibov_ma_month_closing = ibov_ma.resample('ME').last()
ibov_returns = ibov.resample('ME').last().pct_change().dropna()
print(ibov_returns)
# Calculate returns for the first month (missing previously)
ibov_month_opening = ibov.resample('ME').first()
first_month_ibov_returns = (ibov_month_closing.iloc[0] - ibov_month_opening.iloc[0]) / ibov_month_opening.iloc[0]
#
# Model
#
returns = pd.DataFrame(columns=['CDI', 'IBOV', 'Moving Average Method'], index=ibov_returns.index)
returns['CDI'] = cdi_returns
returns['IBOV'] = ibov_returns
choices = pd.DataFrame(columns=['Moving Average Method'], index=ibov_returns.index)
for index, date in enumerate(ibov_returns.index):
if index < len(ibov_returns.index):
if index > ma_months - 1:
if ibov_month_closing.iloc[index] > ibov_ma_month_closing.iloc[index]:
ma_returns = ibov_returns.iloc[index]
ma_choice = 'IBOV'
else:
ma_returns = cdi_returns.iloc[index]
ma_choice = 'CDI'
else:
# For the first months, determine the 'Moving Average Method' as the CDI because of lack of data
ma_returns = cdi_returns.iloc[index]
ma_choice = 'CDI'
returns.loc[date, 'Moving Average Method'] = ma_returns
choices.loc[date, 'Moving Average Method'] = ma_choice
cumulative_returns = (1 + returns).cumprod() - 1
#
# Graph
#
plt.style.use('./mplstyles/financialgraphs.mplstyle')
performance, axes = plt.subplots(figsize=(14, 8))
axes.plot(cumulative_returns['CDI'], label='CDI')
axes.plot(cumulative_returns['IBOV'], label='IBOV')
axes.plot(cumulative_returns['Moving Average Method'], label='Moving Average Method')
axes.yaxis.set_major_formatter(ticker.PercentFormatter(1.0))
plt.xlabel('Time')
plt.ylabel('Performance')
axes.set_title('Performance x Time')
plt.legend(title=f'MA current investment: {choices["Moving Average Method"].iloc[len(ibov_returns.index) - 1]}')
# Add hover tooltips using mplcursors
cursor = mplcursors.cursor()
@cursor.connect("add")
def on_add(sel):
sel.annotation.get_bbox_patch().set(fc='gray', alpha=0.8)
sel.annotation.get_bbox_patch().set_edgecolor('gray')
sel.annotation.arrow_patch.set_color('white')
sel.annotation.arrow_patch.set_arrowstyle('-')
plt.show()