Spaces:
Sleeping
Sleeping
Download lib/backtest_utils.py from ymo2017/jumper-dashboard: direct link, hf CLI and curl.
- Browser
- Download file 2.45 kB
-
https://huggingface.co/spaces/ymo2017/jumper-dashboard/resolve/main/lib/backtest_utils.py
- Command line
-
hf download hf://spaces/ymo2017/jumper-dashboard/lib/backtest_utils.py
-
curl -L -o backtest_utils.py https://huggingface.co/spaces/ymo2017/jumper-dashboard/resolve/main/lib/backtest_utils.py
2.45 kB
| import os | |
| import pandas as pd | |
| import numpy as np | |
| from lib.ticker_config import DEFAULT_TICKERS | |
| def load_data(data_dir, tickers=None): | |
| """Load price data from CSVs in data_dir for the given tickers.""" | |
| if tickers is None: | |
| tickers = DEFAULT_TICKERS | |
| dfs = [] | |
| for ticker in tickers: | |
| # Prefer 20y, fallback to 10y | |
| file_path_20y = os.path.join(data_dir, f"{ticker}_20y_prices.csv") | |
| file_path_10y = os.path.join(data_dir, f"{ticker}_10y_prices.csv") | |
| file_path = file_path_20y if os.path.exists(file_path_20y) else file_path_10y | |
| if os.path.exists(file_path): | |
| df = pd.read_csv(file_path, index_col='Date', parse_dates=True) | |
| df.index = pd.to_datetime(df.index, utc=True).tz_localize(None).normalize() | |
| df = df[['Close']].rename(columns={'Close': ticker}) | |
| dfs.append(df) | |
| else: | |
| print(f"Warning: Data file for {ticker} not found.") | |
| if not dfs: | |
| raise ValueError("No data loaded. Check the data directory.") | |
| combined_df = pd.concat(dfs, axis=1) | |
| combined_df.dropna(inplace=True) | |
| return combined_df | |
| def evaluate_portfolio(df, start_amount, policy_generator, refit=False): | |
| """Standard backtest loop for a given policy generator.""" | |
| if refit and hasattr(policy_generator, 'fit'): | |
| policy_generator.fit(df) | |
| returns = df.pct_change().fillna(0) | |
| portfolio_value = start_amount | |
| portfolio_history = [] | |
| current_weights = {ticker: 0.0 for ticker in df.columns} | |
| holdings_history = [] | |
| metrics_history = [] | |
| for i in range(len(df)): | |
| current_date = df.index[i] | |
| if i > 0: | |
| daily_return = sum(current_weights.get(ticker, 0) * returns.iloc[i][ticker] for ticker in df.columns) | |
| portfolio_value *= (1 + daily_return) | |
| portfolio_history.append(portfolio_value) | |
| target_weights, metrics = policy_generator(current_date, i, df, returns, current_weights) | |
| if target_weights is not None: | |
| current_weights = target_weights | |
| metrics_history.append(metrics) | |
| current_holdings = {k: v for k, v in current_weights.items() if v > 0} | |
| holdings_history.append(current_holdings) | |
| return pd.Series(portfolio_history, index=df.index), pd.DataFrame(holdings_history, index=df.index), pd.DataFrame(metrics_history, index=df.index) | |