instant_volatility.py 1.1 KB

12345678910111213141516171819
  1. from .base_trailing_indicator import BaseTrailingIndicator
  2. import numpy as np
  3. class InstantVolatilityIndicator(BaseTrailingIndicator):
  4. def __init__(self, sampling_length: int = 30, processing_length: int = 15):
  5. super().__init__(sampling_length, processing_length)
  6. def _indicator_calculation(self) -> float:
  7. # The standard deviation should be calculated between ticks and not with a mean of the whole buffer
  8. # Otherwise if the asset is trending, changing the length of the buffer would result in a greater volatility as more ticks would be further away from the mean
  9. # which is a nonsense result. If volatility of the underlying doesn't change in fact, changing the length of the buffer shouldn't change the result.
  10. np_sampling_buffer = self._sampling_buffer.get_as_numpy_array()
  11. vol = np.sqrt(np.sum(np.square(np.diff(np_sampling_buffer))) / np_sampling_buffer.size)
  12. return vol
  13. def _processing_calculation(self) -> float:
  14. # Only the last calculated volatlity, not an average of multiple past volatilities
  15. return self._processing_buffer.get_last_value()