Refactor imports in chart scripts to use package-qualified paths

Updated import statements in `bitcoin_m2_chart.py` and `lagged_oil_unrate_chart_styled.py` to use package-qualified paths for better clarity and consistency. Cleaned up code formatting for improved readability. Added a new output image file for the lagged oil-unrate chart.
This commit is contained in:
thePR0M3TH3AN committed 2025-05-31 10:09:37 -04:00
1 parent e5b1d091c5
commit 040b45b093
4 files changed
+25 -24

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

+2 -2
View File
@@ -20,8 +20,8 @@ import matplotlib.pyplot as plt
import pandas as pd import pandas as pd
from dateutil.relativedelta import relativedelta from dateutil.relativedelta import relativedelta
# IMPORTANT: import common directly (no "scripts." prefix) # IMPORTANT: use the package‐qualified import
from common import fetch_series_db, save_figure from scripts.common import fetch_series_db, save_figure
def fetch_series( def fetch_series(
+16 -16
View File
@@ -21,8 +21,8 @@ import matplotlib.ticker as mticker
import pandas as pd import pandas as pd
from dateutil.relativedelta import relativedelta from dateutil.relativedelta import relativedelta
# IMPORTANT: import common directly (no "scripts." prefix) # IMPORTANT: use the package‐qualified import
from common import ( from scripts.common import (
fetch_series_db, fetch_series_db,
save_figure, save_figure,
validate_dataframe, validate_dataframe,
@@ -45,16 +45,16 @@ def fetch_series(
* average WTI daily prices to month-end * average WTI daily prices to month-end
""" """
# Read both series from SQLite # Read both series from SQLite
df = fetch_series_db(["UNRATE", "DCOILWTICO"], start, end, db_path) # :contentReference[oaicite:0]{index=0} df = fetch_series_db(["UNRATE", "DCOILWTICO"], start, end, db_path)
# Extract UNRATE and rename to 'value' # Extract UNRATE and rename to 'value'
unrate = df[["UNRATE"]].rename(columns={"UNRATE": "value"}) unrate = df[["UNRATE"]].rename(columns={"UNRATE": "value"})
# Extract DCOILWTICO (oil price) and rename to 'value' # Extract DCOILWTICO (oil price) and rename to 'value'
oil = df[["DCOILWTICO"]].rename(columns={"DCOILWTICO": "value"}) oil = df[["DCOILWTICO"]].rename(columns={"DCOILWTICO": "value"})
# Resample WTI to month-end average # Resample WTI to month-end average
oil_monthly = oil.resample("M").mean() # :contentReference[oaicite:1]{index=1} oil_monthly = oil.resample("M").mean()
# Ensure UNRATE is at month-end, too # Ensure UNRATE is at month-end, too
unrate.index = unrate.index.to_period("M").to_timestamp("M") # :contentReference[oaicite:2]{index=2} unrate.index = unrate.index.to_period("M").to_timestamp("M")
return unrate, oil_monthly return unrate, oil_monthly
@@ -86,7 +86,7 @@ def plot_lagged(
""" """
# Find overlapping date range # Find overlapping date range
common_start = max(unrate.index.min(), oil.index.min()) common_start = max(unrate.index.min(), oil.index.min())
common_end = min(unrate.index.max(), oil.index.max()) common_end = min(unrate.index.max(), oil.index.max())
print(f"⚠️ Using overlapping range: {common_start.date()} to {common_end.date()}") print(f"⚠️ Using overlapping range: {common_start.date()} to {common_end.date()}")
print(f" - UNRATE range: {unrate.index.min().date()} to {unrate.index.max().date()}") print(f" - UNRATE range: {unrate.index.min().date()} to {unrate.index.max().date()}")
@@ -94,10 +94,10 @@ def plot_lagged(
# Trim series to common range # Trim series to common range
unrate_common = unrate.loc[common_start:common_end] unrate_common = unrate.loc[common_start:common_end]
oil_common = oil.loc[common_start:common_end] oil_common = oil.loc[common_start:common_end]
# Apply lag/lead # Apply lag/lead
oil_shifted = oil_common.shift(offset_months) # Shift by given months oil_shifted = oil_common.shift(offset_months)
fig, ax1 = plt.subplots(figsize=(14, 7)) fig, ax1 = plt.subplots(figsize=(14, 7))
plt.title("Unemployment Rate and US Oil Price", fontsize=20, weight="bold") plt.title("Unemployment Rate and US Oil Price", fontsize=20, weight="bold")
@@ -136,8 +136,8 @@ def plot_lagged(
# Build doubling ticks from $3 upward # Build doubling ticks from $3 upward
min_tick = 3 min_tick = 3
max_val = oil_shifted["value"].max() * 1.1 max_val = oil_shifted["value"].max() * 1.1
ticks = [] ticks = []
i = 0 i = 0
while min_tick * 2**i < max_val: while min_tick * 2**i < max_val:
ticks.append(min_tick * 2**i) ticks.append(min_tick * 2**i)
@@ -158,7 +158,7 @@ def plot_lagged(
# Legends # Legends
lines, labels = ax1.get_legend_handles_labels() lines, labels = ax1.get_legend_handles_labels()
l2, l2l = ax2.get_legend_handles_labels() l2, l2l = ax2.get_legend_handles_labels()
ax1.legend(lines + l2, labels + l2l, loc="upper left", frameon=False, fontsize=12) ax1.legend(lines + l2, labels + l2l, loc="upper left", frameon=False, fontsize=12)
# Footnote with actual ranges # Footnote with actual ranges
@@ -227,7 +227,7 @@ def main() -> plt.Figure:
args = p.parse_args() args = p.parse_args()
start_dt = datetime.fromisoformat(args.start) start_dt = datetime.fromisoformat(args.start)
end_dt = datetime.fromisoformat(args.end) end_dt = datetime.fromisoformat(args.end)
# ─────────────────────────────────────────────────────────────────────── # ───────────────────────────────────────────────────────────────────────
# Fetch both UNRATE and oil; UNRATE may contain NaNs if the last # Fetch both UNRATE and oil; UNRATE may contain NaNs if the last
@@ -237,12 +237,12 @@ def main() -> plt.Figure:
unrate, oil = fetch_series(start_dt, end_dt, args.db) unrate, oil = fetch_series(start_dt, end_dt, args.db)
# Forward‐fill UNRATE to propagate the last known value into any NaN gaps # Forward‐fill UNRATE to propagate the last known value into any NaN gaps
unrate["value"] = unrate["value"].ffill() # :contentReference[oaicite:3]{index=3} unrate["value"] = unrate["value"].ffill()
# Drop any rows where UNRATE is still NaN (e.g., if the entire series started after 'start') # Drop any rows where UNRATE is still NaN (e.g., if the entire series started after 'start')
unrate = unrate.dropna(subset=["value"]) # :contentReference[oaicite:4]{index=4} unrate = unrate.dropna(subset=["value"])
# Drop any rows in 'oil' where the value is NaN (ensures no Nulls remain) # Drop any rows in 'oil' where the value is NaN (ensures no Nulls remain)
oil = oil.dropna(subset=["value"]) # :contentReference[oaicite:5]{index=5} oil = oil.dropna(subset=["value"])
# Align oil to only dates present in UNRATE after cleaning # Align oil to only dates present in UNRATE after cleaning
oil = oil.loc[oil.index.isin(unrate.index)] oil = oil.loc[oil.index.isin(unrate.index)]
+7 -6
View File
@@ -12,7 +12,7 @@ set -euo pipefail
REQ_FILE="requirements.txt" REQ_FILE="requirements.txt"
DATA_DB="data/fred.db" DATA_DB="data/fred.db"
DEFAULT_SCRIPT="scripts/lagged_oil_unrate_chart_styled.py" DEFAULT_MODULE="scripts.lagged_oil_unrate_chart_styled"
# 1) Ensure pip & setuptools are up to date # 1) Ensure pip & setuptools are up to date
echo "🛠 Upgrading pip & setuptools…" echo "🛠 Upgrading pip & setuptools…"
@@ -25,19 +25,20 @@ pip install --upgrade -r "$REQ_FILE"
# 3) Ensure data exists # 3) Ensure data exists
if [[ ! -f "$DATA_DB" ]]; then if [[ ! -f "$DATA_DB" ]]; then
echo "🔄 Data not found—downloading FRED series…" echo "🔄 Data not found—downloading FRED series…"
python scripts/refresh_data.py python -m scripts.refresh_data
fi fi
# 4) Dispatch to the right command # 4) Dispatch to the right command
if [[ $# -eq 0 ]]; then if [[ $# -eq 0 ]]; then
# no args → run default plot # no args → run default plot module with offset 18
CMD=(python "$DEFAULT_SCRIPT" --offset 18) CMD=(python -m "$DEFAULT_MODULE" --offset 18)
elif [[ "$1" == --* ]]; then elif [[ "$1" == --* ]]; then
# args start with -- → forward to default plot # args start with -- → forward to default plot module
CMD=(python "$DEFAULT_SCRIPT" "$@") CMD=(python -m "$DEFAULT_MODULE" "$@")
else else
# first token is script or other command # first token is script or other command
if [[ -f "$1" || "$1" == *.py ]]; then if [[ -f "$1" || "$1" == *.py ]]; then
# If they explicitly say “scripts/whatever.py …” or “some_test.py …”, run as script
CMD=(python "$@") CMD=(python "$@")
else else
CMD=("$@") CMD=("$@")