Create common helpers and refactor charts

This commit is contained in:
thePR0M3TH3AN committed 2025-05-31 08:55:43 -04:00
1 parent de889caa3d
commit e74d35dce6
4 files changed
+93 -136

No files matched your search

+2 -38
View File
@@ -17,21 +17,7 @@ from typing import Iterable
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
import sqlite3
def save_figure(fig: plt.Figure, output: str | None, script_path: str) -> Path:
"""Save ``fig`` to ``output`` or a timestamped path under ``outputs/``."""
out_path = (
Path(output)
if output is not None
else Path("outputs")
/ f"{Path(script_path).stem}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
)
out_path.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(out_path)
print(f"Saved figure to {out_path}")
return out_path
from scripts.common import fetch_series_db, save_figure
def fetch_series_multi(
@@ -41,29 +27,7 @@ def fetch_series_multi(
db_path: str | Path = Path("data/fred.db"),
) -> pd.DataFrame:
"""Load one or more FRED series from a local SQLite DB."""
db_path = Path(db_path)
if not db_path.exists():
raise FileNotFoundError(
f"{db_path} not found. Run scripts/refresh_data.py on a machine with internet, commit the DB, then retry."
)
frames: list[pd.DataFrame] = []
with sqlite3.connect(db_path) as conn:
for name in series:
df = pd.read_sql(
f"SELECT date, {name} FROM {name}",
conn,
parse_dates=["date"],
index_col="date",
).loc[start:end]
df.rename(columns={name: name}, inplace=True)
frames.append(df)
if not frames:
raise ValueError("No series loaded")
combined = pd.concat(frames, axis=1).sort_index()
return combined
return fetch_series_db(series, start, end, db_path)
def plot_series(df: pd.DataFrame) -> plt.Figure: