Spaces:
Sleeping
Sleeping
File size: 2,429 Bytes
cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d b95fff2 cbdae8d | 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 | import numpy as np
import pandas as pd
from data.schema import Col
REQUIRED_PORTFOLIO_COLUMNS = {
Col.POSITION,
Col.FACTOR,
Col.QUANTITY,
Col.MULTIPLIER,
Col.PRICE_UNIT,
Col.PRICE_CURRENCY,
}
def validate_inputs(
prices: pd.DataFrame,
portfolio: pd.DataFrame,
return_methods: dict[str, str],
) -> None:
if prices.index.has_duplicates:
raise ValueError(
"Prices contain duplicate dates."
)
missing = (
REQUIRED_PORTFOLIO_COLUMNS
- set(portfolio.columns)
)
if missing:
raise ValueError(
f"Missing portfolio columns: {sorted(missing)}"
)
if portfolio[Col.POSITION].duplicated().any():
raise ValueError(
"Portfolio contains duplicated positions."
)
if not np.isfinite(
portfolio[Col.QUANTITY].astype(float)
).all():
raise ValueError(
"Portfolio contains non-finite quantities."
)
factors = set(portfolio[Col.FACTOR])
missing_prices = factors - set(prices.columns)
if missing_prices:
raise ValueError(
f"No price series found for: "
f"{sorted(missing_prices)}"
)
missing_methods = factors - set(return_methods)
if missing_methods:
raise ValueError(
f"No return method for: "
f"{sorted(missing_methods)}"
)
def align_prices(
prices: pd.DataFrame,
factors: list[str],
lookback: int | None,
) -> pd.DataFrame:
"""
Keep the factors held in the portfolio, on dates where all of
them are quoted, limited to the last `lookback` returns
(None = use the full history).
"""
aligned = (
prices[factors]
.apply(pd.to_numeric, errors="raise")
.dropna(how="any")
)
required = (lookback or 2) + 1
if len(aligned) < required:
raise ValueError(
f"Not enough price observations: "
f"{len(aligned)} available, need at least {required}."
)
if lookback:
aligned = aligned.tail(lookback + 1)
return aligned
def zero_change_share(
prices: pd.DataFrame,
) -> pd.Series:
"""
Share of days on which each price did not move.
High values point to stale (illiquid or manually
rolled) quotes, which understate volatility.
"""
return (
prices.diff().iloc[1:] == 0
).mean()
|