forked from Hvass-Labs/FinanceOps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
62 lines (49 loc) · 1.85 KB
/
utils.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
########################################################################
#
# Various utility functions.
#
########################################################################
#
# This file is part of FinanceOps:
#
# https://github.com/Hvass-Labs/FinanceOps
#
# Published under the MIT License. See the file LICENSE for details.
#
# Copyright 2021 by Magnus Erik Hvass Pedersen
#
########################################################################
import numpy as np
########################################################################
def linear_map(x, x_lo, x_hi, y_lo, y_hi, clip=False):
"""
Linear map of input `x` to output `y` where:
- `x == x_lo` => `y == y_lo`
- `x == x_hi` => `y == y_hi`
Output `y` can optionally be clipped between `y_lo` and `y_hi`.
:param x: Array compatible with numpy.
:param x_lo: Scalar value. See function description.
:param x_hi: Scalar value. See function description.
:param y_lo: Scalar value. See function description.
:param y_hi: Scalar value. See function description.
:param clip:
Clip output. If set to the boolean value `True` or the string 'both',
then the output is clipped between both `y_lo` and `y_hi`.
If set to the string 'lo' then only clip the lower bound using `y_lo`.
If set to the string 'hi' then only clip the upper bound using `y_hi`.
:return: Array of same size as input `x`.
"""
# Parameters for the linear mapping.
a = (y_hi - y_lo) / (x_hi - x_lo)
b = y_lo - a * x_lo
# Linear mapping.
y = a * x + b
# Optional clipping.
if clip == 'both' or clip is True:
y = np.clip(y, y_lo, y_hi)
elif clip == 'lo':
y = np.maximum(y, y_lo)
elif clip == 'hi':
y = np.minimum(y, y_hi)
return y
########################################################################