-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbbr.py
More file actions
63 lines (49 loc) · 1.7 KB
/
Copy pathbbr.py
File metadata and controls
63 lines (49 loc) · 1.7 KB
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
from collections import namedtuple
import numba
import numpy as np
from jesse.helpers import get_candle_source, slice_candles
BBR = namedtuple('bbr', ['upper', 'middle', 'lower', 'ratio'])
def bbr(candles: np.ndarray, length: int = 20, source_type="close", mult: float = 2.0, sequential=False) -> BBR:
# Bollinger Bands with Ratio % in pure Python & Numba
# github.com/ysdede
"""
:param candles: np.ndarray
:param length: int - default: 2
:param source_type: str - default: close
:param mult: float - default: 2.0
:param sequential: bool - default: False
:return: Union[float, np.ndarray]
"""
if length < 1 or mult < 0.001:
raise ValueError('Bad parameters.')
if len(candles.shape) == 1:
source = candles
else:
candles = slice_candles(candles, sequential)
source = get_candle_source(candles, source_type=source_type)
out = np.empty(source.size)
basis = sma(source, length, out)
upper, lower, ratio = bb_fast(mult, source, length, basis)
if sequential:
return BBR(upper, basis, lower, ratio)
else:
return BBR(upper[-1], basis[-1], lower[-1], ratio[-1])
@numba.njit(nopython=True)
def bb_fast(mult, source, length, basis):
dev = np.multiply(mult, np.std(source[-length:]))
upper = basis + dev
lower = basis - dev
ratio = (source - lower) / (upper - lower)
return upper, lower, ratio
@numba.njit(nopython=True)
def sma(src, length, out):
asum = 0.0
count = 0
for i in range(length):
asum += src[i]
count += 1
out[i] = asum / count
for i in range(length, src.size):
asum += src[i] - src[i - length]
out[i] = asum / count
return out