@@ -51,6 +51,15 @@ def _std(values: Iterable[float]) -> float:
5151 return float (sqrt (variance ))
5252
5353
54+ def _sample_std (values : Iterable [float ]) -> float :
55+ values = tuple (values )
56+ if len (values ) < 2 :
57+ raise ValueError ("sample std requires at least two values" )
58+ mean_value = _mean (values )
59+ variance = sum ((value - mean_value ) ** 2 for value in values ) / (len (values ) - 1 )
60+ return float (sqrt (variance ))
61+
62+
5463def _tail_mean (values : tuple [float , ...], window : int ) -> float :
5564 if len (values ) < window :
5665 raise ValueError ("insufficient history for rolling mean" )
@@ -63,6 +72,18 @@ def _tail_std(values: tuple[float, ...], window: int) -> float:
6372 return _std (values [- window :])
6473
6574
75+ def _tail_realized_volatility (values : tuple [float , ...], window : int ) -> float :
76+ if len (values ) < window + 1 :
77+ raise ValueError ("insufficient history for realized volatility" )
78+ tail_values = values [- (window + 1 ):]
79+ returns : list [float ] = []
80+ for previous , current in zip (tail_values , tail_values [1 :]):
81+ if previous == 0.0 :
82+ raise ValueError ("realized volatility requires non-zero prices" )
83+ returns .append ((current / previous ) - 1.0 )
84+ return float (_sample_std (returns ) * sqrt (252 ))
85+
86+
6687def _compute_rsi (values : tuple [float , ...], * , window : int = 14 ) -> tuple [float , ...]:
6788 if len (values ) < window + 1 :
6889 raise ValueError ("insufficient history for RSI" )
@@ -161,6 +182,7 @@ def build_semiconductor_rotation_indicators_from_history(
161182 )
162183 soxx_bb_mid = _tail_mean (soxx_close , 20 )
163184 soxx_bb_std = _tail_std (soxx_close , 20 )
185+ soxx_realized_volatility_20 = _tail_realized_volatility (soxx_close , 20 )
164186 return {
165187 "soxl" : {
166188 "price" : float (soxl_close [- 1 ]),
@@ -176,6 +198,8 @@ def build_semiconductor_rotation_indicators_from_history(
176198 "bb_mid" : soxx_bb_mid ,
177199 "bb_upper" : soxx_bb_mid + 2.0 * soxx_bb_std ,
178200 "bb_lower" : soxx_bb_mid - 2.0 * soxx_bb_std ,
201+ "realized_volatility" : soxx_realized_volatility_20 ,
202+ "realized_volatility_20" : soxx_realized_volatility_20 ,
179203 },
180204 }
181205
0 commit comments