Coverage for source/indicators/volatility_indicator.py: 42%

12 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-07-26 15:49 +0000

1# indicators/volatility_indicator.py 

2 

3# global imports 

4import pandas as pd 

5 

6# local imports 

7from source.indicators import IndicatorHandlerBase 

8 

9class VolatilityIndicatorHandler(IndicatorHandlerBase): 

10 """ 

11 Implements volatility indicator. It measures the price fluctuations over a 

12 certain period of time. Calculated data can not be directly mapped to input 

13 data and should be treated as the separate chart. 

14 """ 

15 

16 def __init__(self, window_size: int = 10) -> None: 

17 """ 

18 Class constructor. Initializes the window size for volatility calculation. 

19 

20 Parameters: 

21 window_size (int): Size of the window used for calculating volatility. 

22 """ 

23 

24 self.__window_size = window_size 

25 

26 def calculate(self, data: pd.DataFrame) -> pd.DataFrame: 

27 """ 

28 Calculates volatility indicator values for given data. 

29 

30 Parameters: 

31 data (pd.DataFrame): Data frame with input data. 

32 

33 Returns: 

34 (pd.DataFrame): Output data with calculated volatility values. 

35 """ 

36 

37 volatility_df = pd.DataFrame(index = data.index) 

38 volatility_df['volatility'] = data['close'].pct_change(). \ 

39 rolling(window = self.__window_size, min_periods = 1).std() 

40 volatility_df = volatility_df.fillna(0) 

41 

42 max_volatility = volatility_df['volatility'].max() 

43 volatility_df['volatility'] = volatility_df['volatility'] / max_volatility 

44 

45 return volatility_df