File size: 17,380 Bytes
a2afe2f |
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 |
"""Technical Analysis Helpers."""
# pylint: disable=too-many-arguments,too-many-locals,too-many-positional-arguments
from typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple, Union
from warnings import warn
if TYPE_CHECKING:
from pandas import DataFrame, Series, Timestamp
def validate_data(data: list, length: Union[int, List[int]]) -> None:
"""Validate data."""
if isinstance(length, int):
length = [length]
for item in length:
if item > len(data):
raise ValueError(
f"Data length is less than required by parameters: {max(length)}"
)
def parkinson(
data: "DataFrame",
window: int = 30,
trading_periods: Optional[int] = None,
is_crypto: bool = False,
clean=True,
) -> "DataFrame":
"""Parkinson volatility.
Uses the high and low price of the day rather than just close to close prices.
It is useful for capturing large price movements during the day.
Parameters
----------
data : DataFrame
Dataframe of OHLC prices.
window : int [default: 30]
Length of window to calculate over.
trading_periods : Optional[int] [default: 252]
Number of trading periods in a year.
is_crypto : bool [default: False]
If true, trading_periods is defined as 365.
clean : bool [default: True]
Whether to clean the data or not by dropping NaN values.
Returns
-------
DataFrame : results
Dataframe with results.
"""
# pylint: disable=import-outside-toplevel
from numpy import log
if window < 1:
warn("Error: Window must be at least 1, defaulting to 30.")
window = 30
if trading_periods and is_crypto:
warn("is_crypto is overridden by trading_periods.")
if not trading_periods:
trading_periods = 365 if is_crypto else 252
rs = (1.0 / (4.0 * log(2.0))) * ((data["high"] / data["low"]).apply(log)) ** 2.0
def f(v):
return (trading_periods * v.mean()) ** 0.5
result = rs.rolling(window=window, center=False).apply(func=f)
if clean:
return result.dropna()
return result
def standard_deviation(
data: "DataFrame",
window: int = 30,
trading_periods: Optional[int] = None,
is_crypto: bool = False,
clean: bool = True,
) -> "DataFrame":
"""Calculate the Standard deviation.
Measures how widely returns are dispersed from the average return.
It is the most common (and biased) estimator of volatility.
Parameters
----------
data : DataFrame
Dataframe of OHLC prices.
window : int [default: 30]
Length of window to calculate over.
trading_periods : Optional[int] [default: 252]
Number of trading periods in a year.
is_crypto : bool [default: False]
If true, trading_periods is defined as 365.
clean : bool [default: True]
Whether to clean the data or not by dropping NaN values.
Returns
-------
DataFrame : results
Dataframe with results.
"""
# pylint: disable=import-outside-toplevel
from numpy import log, sqrt
if window < 2:
warn("Error: Window must be at least 2, defaulting to 30.")
window = 30
if trading_periods and is_crypto:
warn("is_crypto is overridden by trading_periods.")
if not trading_periods:
trading_periods = 365 if is_crypto else 252
log_return = (data["close"] / data["close"].shift(1)).apply(log)
result = log_return.rolling(window=window, center=False).std() * sqrt(
trading_periods
)
if clean:
return result.dropna()
return result
def garman_klass(
data: "DataFrame",
window: int = 30,
trading_periods: Optional[int] = None,
is_crypto: bool = False,
clean=True,
) -> "DataFrame":
"""Garman-Klass volatility.
Extends Parkinson volatility by taking into account the opening and closing price.
As markets are most active during the opening and closing of a trading session.
It makes volatility estimation more accurate.
Parameters
----------
data : DataFrame
Dataframe of OHLC prices.
window : int [default: 30]
Length of window to calculate over.
trading_periods : Optional[int] [default: 252]
Number of trading periods in a year.
is_crypto : bool [default: False]
If true, trading_periods is defined as 365.
clean : bool [default: True]
Whether to clean the data or not by dropping NaN values.
Returns
-------
DataFrame : results
Dataframe with results.
"""
# pylint: disable=import-outside-toplevel
from numpy import log
if window < 1:
warn("Error: Window must be at least 1, defaulting to 30.")
window = 30
if trading_periods and is_crypto:
warn("is_crypto is overridden by trading_periods.")
if not trading_periods:
trading_periods = 365 if is_crypto else 252
log_hl = (data["high"] / data["low"]).apply(log)
log_co = (data["close"] / data["open"]).apply(log)
rs = 0.5 * log_hl**2 - (2 * log(2) - 1) * log_co**2
def f(v):
return (trading_periods * v.mean()) ** 0.5
result = rs.rolling(window=window, center=False).apply(func=f)
if clean:
return result.dropna()
return result
def hodges_tompkins(
data: "DataFrame",
window: int = 30,
trading_periods: Optional[int] = None,
is_crypto: bool = False,
clean=True,
) -> "DataFrame":
"""Hodges-Tompkins volatility.
Is a bias correction for estimation using an overlapping data sample.
It produces unbiased estimates and a substantial gain in efficiency.
Parameters
----------
data : DataFrame
Dataframe of OHLC prices.
window : int [default: 30]
Length of window to calculate over.
trading_periods : Optional[int] [default: 252]
Number of trading periods in a year.
is_crypto : bool [default: False]
If true, trading_periods is defined as 365.
clean : bool [default: True]
Whether to clean the data or not by dropping NaN values.
Returns
-------
DataFrame : results
Dataframe with results.
Example
-------
>>> data = obb.equity.price.historical('BTC-USD')
>>> df = obb.technical.hodges_tompkins(data, is_crypto = True)
"""
# pylint: disable=import-outside-toplevel
from numpy import log, sqrt
if window < 2:
warn("Error: Window must be at least 2, defaulting to 30.")
window = 30
if trading_periods and is_crypto:
warn("is_crypto is overridden by trading_periods.")
if not trading_periods:
trading_periods = 365 if is_crypto else 252
log_return = (data["close"] / data["close"].shift(1)).apply(log)
vol = log_return.rolling(window=window, center=False).std() * sqrt(trading_periods)
h = window
n = (log_return.count() - h) + 1
adj_factor = 1.0 / (1.0 - (h / n) + ((h**2 - 1) / (3 * n**2)))
result = vol * adj_factor
if clean:
return result.dropna()
return result
def rogers_satchell(
data: "DataFrame",
window: int = 30,
trading_periods: Optional[int] = None,
is_crypto: bool = False,
clean=True,
) -> "Series":
"""Rogers-Satchell Estimator.
Is an estimator for measuring the volatility with an average return not equal to zero.
Unlike Parkinson and Garman-Klass estimators, Rogers-Satchell incorporates a drift term,
mean return not equal to zero.
Parameters
----------
data : DataFrame
Dataframe of OHLC prices.
window : int [default: 30]
Length of window to calculate over.
trading_periods : Optional[int] [default: 252]
Number of trading periods in a year.
is_crypto : bool [default: False]
If true, trading_periods is defined as 365.
clean : bool [default: True]
Whether to clean the data or not by dropping NaN values.
Returns
-------
Series : results
Pandas Series with results.
"""
# pylint: disable=import-outside-toplevel
from numpy import log
if window < 1:
warn("Error: Window must be at least 1, defaulting to 30.")
window = 30
if trading_periods and is_crypto:
warn("is_crypto is overridden by trading_periods.")
if not trading_periods:
trading_periods = 365 if is_crypto else 252
log_ho = (data["high"] / data["open"]).apply(log)
log_lo = (data["low"] / data["open"]).apply(log)
log_co = (data["close"] / data["open"]).apply(log)
rs = log_ho * (log_ho - log_co) + log_lo * (log_lo - log_co)
def f(v):
return (trading_periods * v.mean()) ** 0.5
result = rs.rolling(window=window, center=False).apply(func=f)
if clean:
return result.dropna()
return result
def yang_zhang(
data: "DataFrame",
window: int = 30,
trading_periods: Optional[int] = None,
is_crypto: bool = False,
clean=True,
) -> "DataFrame":
"""Yang-Zhang Volatility.
Is the combination of the overnight (close-to-open volatility).
It is a weighted average of the Rogers-Satchell volatility and the open-to-close volatility.
Parameters
----------
data : DataFrame
Dataframe of OHLC prices.
window : int [default: 30]
Length of window to calculate standard deviation.
trading_periods : Optional[int] [default: 252]
Number of trading periods in a year.
is_crypto : bool [default: False]
If true, trading_periods is defined as 365.
clean : bool [default: True]
Whether to clean the data or not by dropping NaN values.
Returns
-------
DataFrame : results
Dataframe with results.
"""
# pylint: disable=import-outside-toplevel
from numpy import log, sqrt
if window < 2:
warn("Error: Window must be at least 2, defaulting to 30.")
window = 30
if trading_periods and is_crypto:
warn("is_crypto is overridden by trading_periods.")
if not trading_periods:
trading_periods = 365 if is_crypto else 252
log_ho = (data["high"] / data["open"]).apply(log)
log_lo = (data["low"] / data["open"]).apply(log)
log_co = (data["close"] / data["open"]).apply(log)
log_oc = (data["open"] / data["close"].shift(1)).apply(log)
log_oc_sq = log_oc**2
log_cc = (data["close"] / data["close"].shift(1)).apply(log)
log_cc_sq = log_cc**2
rs = log_ho * (log_ho - log_co) + log_lo * (log_lo - log_co)
close_vol = log_cc_sq.rolling(window=window, center=False).sum() * (
1.0 / (window - 1.0)
)
open_vol = log_oc_sq.rolling(window=window, center=False).sum() * (
1.0 / (window - 1.0)
)
window_rs = rs.rolling(window=window, center=False).sum() * (1.0 / (window - 1.0))
k = 0.34 / (1.34 + (window + 1) / (window - 1))
result = (open_vol + k * close_vol + (1 - k) * window_rs).apply(sqrt) * sqrt(
trading_periods
)
if clean:
return result.dropna()
return result
def calculate_cones(
data: "DataFrame",
lower_q: float,
upper_q: float,
is_crypto: bool,
model: Literal[
"std",
"parkinson",
"garman_klass",
"hodges_tompkins",
"rogers_satchell",
"yang_zhang",
],
trading_periods: Optional[int] = None,
) -> "DataFrame":
"""Calculate Cones."""
# pylint: disable=import-outside-toplevel
from pandas import DataFrame
estimator = DataFrame()
if lower_q > upper_q:
lower_q, upper_q = upper_q, lower_q
if (lower_q >= 1) or (upper_q >= 1):
raise ValueError("Error: lower_q and upper_q must be between 0 and 1")
lower_q_label = str(int(lower_q * 100))
upper_q_label = str(int(upper_q * 100))
quantiles = [lower_q, upper_q]
windows = [3, 10, 30, 60, 90, 120, 150, 180, 210, 240, 300, 360]
min_ = []
max_ = []
median = []
top_q = []
bottom_q = []
realized = []
allowed_windows = []
data = data.sort_index(ascending=True)
model_functions = {
"std": standard_deviation,
"parkinson": parkinson,
"garman_klass": garman_klass,
"hodges_tompkins": hodges_tompkins,
"rogers_satchell": rogers_satchell,
"yang_zhang": yang_zhang,
}
for window in windows:
estimator = model_functions[model]( # type: ignore
window=window,
data=data,
is_crypto=is_crypto,
trading_periods=trading_periods,
)
if estimator.empty:
continue
min_.append(estimator.min()) # type: ignore
max_.append(estimator.max()) # type: ignore
median.append(estimator.median()) # type: ignore
top_q.append(estimator.quantile(quantiles[1])) # type: ignore
bottom_q.append(estimator.quantile(quantiles[0])) # type: ignore
realized.append(estimator.iloc[-1]) # type: ignore
allowed_windows.append(window)
df_ = [realized, min_, bottom_q, median, top_q, max_]
df_windows = allowed_windows
df = DataFrame(df_, columns=df_windows)
df = df.rename(
index={
0: "realized",
1: "min",
2: f"lower_{lower_q_label}%",
3: "median",
4: f"upper_{upper_q_label}%",
5: "max",
}
)
cones_df = df.copy()
return cones_df.transpose().reset_index().rename(columns={"index": "window"})
def clenow_momentum(
values: "Series", window: int = 90
) -> Tuple[float, float, "Series"]:
"""Clenow Volatility Adjusted Momentum.
This is defined as the regression coefficient on log prices multiplied by the R^2
value of the regression.
Parameters
----------
values: Series
Values to perform regression for
window: int
Length of look back period
Returns
-------
float:
R2 of fit to log data
float:
Coefficient of linear regression
Series:
Values for best fit line
"""
# pylint: disable=import-outside-toplevel
from numpy import arange, exp, log
from pandas import Series
from sklearn.linear_model import LinearRegression
if len(values) < window:
raise ValueError(f"Calculation asks for at least last {window} days of data")
values = values[-window:]
y = log(values)
X = arange(len(y)).reshape(-1, 1) # pylint: disable=invalid-name
lr = LinearRegression()
lr.fit(X, y)
r2 = lr.score(X, y)
coef = lr.coef_[0]
annualized_coef = (exp(coef) ** 252) - 1
return r2, annualized_coef, Series(lr.predict(X))
def calculate_fib_levels(
data: "DataFrame",
close_col: str,
limit: int = 120,
start_date: Optional[Any] = None,
end_date: Optional[Any] = None,
) -> Tuple["DataFrame", "Timestamp", "Timestamp", float, float, str]:
"""Calculate Fibonacci levels.
Parameters
----------
data : DataFrame
Dataframe of prices
close_col : str
Column name of close prices
limit : int
Days to look back for retracement
start_date : Any
Custom start date for retracement
end_date : Any
Custom end date for retracement
Returns
-------
df : DataFrame
Dataframe of fib levels
min_date: Timestamp
Date of min point
max_date: Timestamp:
Date of max point
min_pr: float
Price at min point
max_pr: float
Price at max point
"""
# pylint: disable=import-outside-toplevel
from pandas import DataFrame
if close_col not in data.columns:
raise ValueError(f"Column {close_col} not in data")
if start_date and end_date:
if start_date not in data.index:
date0 = data.index[data.index.get_indexer([end_date], method="nearest")[0]]
warn(f"Start date not in data. Using nearest: {date0}")
else:
date0 = start_date
if end_date not in data.index:
date1 = data.index[data.index.get_indexer([end_date], method="nearest")[0]]
warn(f"End date not in data. Using nearest: {date1}")
else:
date1 = end_date
data0 = data.loc[date0, close_col]
data1 = data.loc[date1, close_col]
min_pr = min(data0, data1)
max_pr = max(data0, data1)
if min_pr == data0:
min_date = date0
max_date = date1
else:
min_date = date1
max_date = date0
else:
data_to_use = data.iloc[-limit:, :][close_col]
min_pr = data_to_use.min()
min_date = data_to_use.idxmin()
max_pr = data_to_use.max()
max_date = data_to_use.idxmax()
fib_levels = [0, 0.235, 0.382, 0.5, 0.618, 0.65, 1]
lvl_text: str = "left" if min_date < max_date else "right"
if min_date > max_date:
min_date, max_date = max_date, min_date
min_pr, max_pr = max_pr, min_pr
price_dif = max_pr - min_pr
levels = [
round(max_pr - price_dif * f_lev, (2 if f_lev > 1 else 4))
for f_lev in fib_levels
]
df = DataFrame()
df["Level"] = fib_levels
df["Level"] = df["Level"].apply(lambda x: str(x * 100) + "%")
df["Price"] = levels
return df, min_date, max_date, min_pr, max_pr, lvl_text
|