Indicator Parameters
Different assets, different exchanges, different market conditions, different participants, all mixed and shaken means: the same indicator has to be used with different parameters for different scenarios.
Luckily, the parametrization of the indicators is realized via the standard
named arguments mechanism already present in Python, the **kwargs
(which is
the standard notation and stands for "keyword arguments")
Default Params
Getting the names and default values for each indicator can be done through the
documentation or the params
class attribute.
Over the documentation with
import btalib print(btalib.sma.__doc__)
With the following output (focusing on the parameters section)
Params: - period (default: 30) Period for the moving average calculation
The sma
supports a single parameter named period
with a default value of
30
.
It may also be found by accessing the class params
attribute.
import btalib print(btalib.sma.params)
which has the following output
{'period': 30}
I.e.: it is a dictionary containing the name and the default value for the parameter.
Execution parameters
Passing it as keyword arguments (aka **kwargs
) suffices to modify the
behavior of the indicator. An example with the sma
running with a period of
4
instead the default 30
import btalib import pandas as pd # Read a csv file into a pandas dataframe df = pd.read_csv('2006-day-001.txt', parse_dates=True, index_col='Date') sma = btalib.sma(df, period=4) print(sma.params)
The output now is
{'period': 4}
Using params as dict
The params
class attribute is in fact a dict
, and it can therefore be
used as one.
But the params
instance attribute is not a dict
. It can be
partially used as one, but in order to leave as many names as possible free for
the parameter names, only the visible method keys()
of a dictionary is
implemented
Note
Implementing keys()
is not random choice. It is needed to support the
**kwargs
expansion notation.
For example
import btalib import pandas as pd # Read a csv file into a pandas dataframe df = pd.read_csv('2006-day-001.txt', parse_dates=True, index_col='Date') sma = btalib.sma(df, period=4) params_dict = dict(sma.params) print(params_dict)
with output (as expected)
{'period': 4}
Hint
The same could have been achieved with params_dict = dict(**sma.params)
or params_dict = dict(sma.params)
Params can also be iterated to get the keys
(i.e.: param names) and values
may be accessed using the standard [item]
notation.
import btalib import pandas as pd # Read a csv file into a pandas dataframe df = pd.read_csv('2006-day-001.txt', parse_dates=True, index_col='Date') sma = btalib.sma(df, period=4) for k in sma.params: print('name: {} - value: {}'.format(k, sma.params[k]))
and a new style is used, but nothing new under sun, the same old period is shown.
name: period - value: 4