Spaces:
Sleeping
Sleeping
Download data/validation.py from MinsaitEU/VaR_model: direct link, hf CLI and curl.
- Browser
- Download file 2.43 kB
-
https://huggingface.co/spaces/MinsaitEU/VaR_model/resolve/main/data/validation.py
- Command line
-
hf download hf://spaces/MinsaitEU/VaR_model/data/validation.py
-
curl -L -o validation.py https://huggingface.co/spaces/MinsaitEU/VaR_model/resolve/main/data/validation.py
2.43 kB
| 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() | |