-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy path04-heatmap.py
53 lines (42 loc) · 1.42 KB
/
04-heatmap.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
import datetime
import pandas_ta as ta
import pandas as pd
from backtesting import Backtest
from backtesting import Strategy
from backtesting.lib import crossover
from backtesting.test import GOOG
import matplotlib.pyplot as plt
import seaborn as sns
def optim_func(series):
if series['# Trades'] < 10:
return -1
else:
return series['Equity Final [$]']/series['Exposure Time [%]']
class RsiOscillator(Strategy):
upper_bound = 70
lower_bound = 30
rsi_window = 14
# Do as much initial computation as possible
def init(self):
self.rsi = self.I(ta.rsi, pd.Series(self.data.Close), self.rsi_window)
# Step through bars one by one
# Note that multiple buys are a thing here
def next(self):
if crossover(self.rsi, self.upper_bound):
self.position.close()
elif crossover(self.lower_bound, self.rsi):
self.buy()
bt = Backtest(GOOG, RsiOscillator, cash=10_000, commission=.002)
stats, heatmap = bt.optimize(
upper_bound = range(55, 85, 5),
lower_bound = range(10, 45, 5),
rsi_window = range(10, 30, 2),
maximize = optim_func,
constraint = lambda param: param.upper_bound > param.lower_bound,
return_heatmap=True,
)
# choose your colormaps from here
# https://matplotlib.org/stable/tutorials/colors/colormaps.html
hm = heatmap.groupby(["upper_bound","lower_bound"]).mean().unstack()
sns.heatmap(hm, cmap="plasma")
plt.show()