-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactor_basics.py
More file actions
34 lines (24 loc) · 1.14 KB
/
Copy pathfactor_basics.py
File metadata and controls
34 lines (24 loc) · 1.14 KB
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
"""Transparent, educational factor calculations for local research data."""
from __future__ import annotations
from collections.abc import Iterable
def simple_returns(closes: Iterable[float]) -> list[float]:
"""Calculate close-to-close simple returns."""
prices = list(closes)
if any(price <= 0 for price in prices):
raise ValueError("closing prices must be positive")
return [round(current / previous - 1, 6) for previous, current in zip(prices, prices[1:])]
def moving_average(values: Iterable[float], window: int) -> list[float | None]:
"""Return a trailing arithmetic average, with ``None`` before warm-up."""
if window < 1:
raise ValueError("window must be at least 1")
numbers = list(values)
result: list[float | None] = [None] * min(window - 1, len(numbers))
result.extend(
round(sum(numbers[index - window + 1 : index + 1]) / window, 6)
for index in range(window - 1, len(numbers))
)
return result
if __name__ == "__main__":
closes = [10.0, 10.5, 10.2, 10.8, 11.0]
print("returns:", simple_returns(closes))
print("3-day average:", moving_average(closes, 3))