Econ detrending correlation

From XuShuwenn/RedAct · View interactive version

Econ detrending correlation is an AI agent skill from the GitHub repository XuShuwenn/RedAct. Apply Hodrick-Prescott filter to detrend economic time series and calculate Pearson correlation between consumption and investment.

How to use this skill

Skill file

Economic Time Series Detrending and Correlation

When to Use

Input Files

Key Steps

  1. Inspect each input workbook first with spreadsheet-aware tools: print sheet names, column labels, and representative top/middle/bottom rows before coding against assumed headers or row formats; identify the actual header row, where annual data begins, the correct Total/value column, and where quarterly/footer sections start

1b. During inspection, explicitly note for each file: sheet used, header row, year/label column, value column, where annual rows start, where annual rows stop and quarterly rows begin, and whether the bottom block contains continuation-style quarter labels that require carrying forward the active year/header context.

1c. Validate the intended value column with one known clearly annual row: print the year label plus candidate numeric columns and confirm the chosen Total/value column gives a sensible series value before writing the extractor.

1d. Base extraction rules on the labels you actually observe in each workbook (for example annual labels like 1973. and quarterly labels like 2024: I., II., III p.) instead of hard-coded row numbers or assumed repeated layouts.

1e. Build and validate the pipeline in stages: (a) workbook structure inspection, (b) nominal series extraction, (c) optional latest-year aggregation, (d) CPI alignment/deflation, (e) log + HP filter, (f) correlation + answer write-back. After each stage, print a compact diagnostic and do not proceed if the stage output is empty, misaligned, or inconsistent with the inspected workbook structure.

1a. Before building the pipeline, restate the requested methodology from the task prompt and confirm it matches this skill's default sequence; do not assume HP filtering, CPI deflation, log transformation, Pearson correlation, or special 2024 handling unless the task instructions or inspected source structure support them.

1aa. Make an explicit latest-year decision before writing extraction code: either (a) use reported annual observations only, or (b) derive the latest year from quarterly rows. Prefer annual-only when the direct annual sample already answers the task; use quarterly derivation only when the task explicitly requires the latest available year or the workbook lacks the needed annual endpoint.

1ab. If the prompt and workbook evidence indicate a simpler annual-only workflow, use that simpler workflow; do not add quarterly annualization, extra transformations, or sample extensions unless they are necessary for the requested result.

1ac. Before implementation, write a one-line plan stating the requested output artifact and exact transforms to apply. Keep the standard pipeline (nominal → real via CPI → log → HP filter → Pearson correlation) only when the prompt explicitly asks for detrended real-series comovement; if that plan does not explicitly call for correlation and /root/answer.txt, do not produce them by default.

1ad. Check library availability before writing the main pipeline (at minimum Excel-reading support and a preferred HP-filter implementation such as statsmodels); if a preferred package is unavailable, choose the simplest supported alternative before coding further.

  1. Extract Personal Consumption Expenditures (Total, column 1) and PFI (Total, column 1) from their ERP tables separately

2a. For each ERP workbook, identify the year/label column and numeric value column from that workbook itself; do not reuse row offsets, header positions, or footer boundaries from the other ERP file.

2a.i. Confirm the target value column by combining header labels with representative sample row values rather than trusting column position or an Unnamed label alone; verify it is the intended Total series before extraction.

2b. Print a small sample of extracted annual year→value pairs for each series before merging so wrong-row or wrong-column extraction is caught early.

  1. Build independent year→value mappings for each series, then merge by year; do not assume matching row numbers across the two files

3a. Normalize extracted year labels before filtering or merging: trim whitespace/trailing punctuation so labels like 1973. parse to the intended year instead of being silently dropped.

3aa. If an expected year is missing after extraction or merge, print the raw year labels alongside the normalized labels for the affected rows and fix normalization/parsing before continuing; do not debug coverage gaps only from aggregate counts.

3b. After merging, print the overlapping year span and observation count, plus a few first/last merged rows, before proceeding.

3c. Keep these diagnostics lightweight and repeatable: after nominal extraction, after any latest-year quarterly aggregation, and after CPI alignment, print start year, end year, and count so the final successful run still shows the full sample progression.

3d. Preserve each source as an explicit year→value mapping until the final aligned merge; do not join by row position or rely on workbook order alone.

3e. When the merged sample is ready, verify all three series (consumption, investment, CPI) share the same annual index before any deflation, logging, or filtering.

  1. Handle quarterly data at the end of the tables only after confirming a quarterly-derived latest year is actually needed. Inspect the bottom rows first; if the task requires extending the sample beyond the completed annual rows, statefully track the active year, enumerate every matched latest-year quarter row from that active-year block (including inherited labels like II./III p. after 2024: I.), stop when notes/source/footer text begins, and compute the annual latest-year value as the mean of all available quarters shown in the source table.

4a. Before constructing any latest-year annual value from quarters, verify whether the workbook already provides the latest usable completed annual observation range. Default to the completed annual sample; only add a derived latest-year point when the task explicitly requires the latest available year or the source clearly lacks an annual value that the task still expects you to use.

4b. If you do use quarterly rows to form 2024, treat quarter coverage diagnostics as a gate, not a note: compare the visible quarter count in the workbook against the quarters actually captured by the parser, record why the conversion is necessary, and immediately reprint start year, end year, and observation count so any unexpected shift in sample boundaries is caught before merging or correlation.

4b1. Before writing the parser, inspect the exact displayed latest-year row-label text and continuation-row formatting in each workbook, then match only rows demonstrably belonging to the active latest-year block.

4b2. When later quarter rows inherit the year from the first labeled row (for example 2024: I. followed by II. / III.), carry forward that active year while parsing and print the exact matched labels so inherited-quarter attachment is visibly verified before annualizing.

4c. Decide explicitly whether the latest year should enter the annual HP-filter sample. If the annual table is not yet complete but the task asks for the latest available data and the workbook shows multiple latest-year quarters, aggregate the available quarters consistently and state that choice in diagnostics. If the workbook shows only a genuinely sparse partial year (for example just 1 quarter) and the task does not clearly require including it, exclude that year and use the last completed annual observation.

  1. Validate extraction results before proceeding: ensure annual observations are non-empty, years are in expected order, and 2024 handling did not accidentally pull quarters from earlier years, miss available quarters, or remove the series

5a. Before any CPI merge or statistical transformation, confirm the working extraction is annual-only except for an explicitly documented latest-year quarterly-to-annual conversion; do not let raw quarterly rows flow into the merged analysis dataset.

5b. Print a concise frequency sanity check for each extracted series (for example first/last annual labels kept, any quarter labels captured for latest-year handling, final annual observation count).

  1. Inspect /root/CPI.xlsx with targeted output (sheet names, exact column names, and sample rows), then confirm the actual year column, CPI/deflator column, and unit/scaling before deflating; if the workbook already provides a target-year deflator/ratio, use that column directly rather than rebuilding it from a guessed schema

6a. Before running the full pipeline, verify prerequisites up front: confirm the CPI workbook covers the full intended analysis span after any latest-year decision and that the HP-filter library you plan to use (for example statsmodels) imports successfully; if either prerequisite fails, adjust the plan before doing the full extraction/merge workflow.

6b. When the CPI workbook exposes a clearly named target-year column (for example CPI_2024 or an equivalent deflator-to-target-year field), prefer that inspected column directly for real-value conversion and print the exact column name chosen; do not substitute a different CPI formula unless the workbook structure requires it.

  1. Before HP filtering, verify the CPI-aligned real consumption and real investment series use the identical final year list, and print a short diagnostic showing overlapping years, sample real values, and the exact deflation formula used

7a. Keep the workflow staged and auditable: finish nominal extraction and year alignment first, then merge CPI, then compute real series, then log/HP/correlation. At each handoff, print a few sample year→value rows so extraction mistakes are caught before statistical transformation hides them.

7b. Before division, np.log, or HP filtering, explicitly coerce the extracted nominal values, CPI values, and merged real-series arrays to numeric dtypes and confirm there are no object/string leftovers or unexpected non-numeric entries.

  1. Apply the required transformation order exactly: nominal → real via CPI → natural log → Hodrick-Prescott filter with λ=100

8a. Keep this order unchanged even if workbook cleanup is messy: first align annual nominal series with CPI by year, then deflate both with the same CPI basis, then take natural logs of the real series, then apply the HP filter to those logged real series, and finally correlate the resulting cyclical components.

8b. Before running the HP-filter step, confirm the intended library is importable (prefer statsmodels.tsa.filters.hp_filter.hpfilter); if import fails, stop and resolve the dependency or choose another trusted implementation before continuing so the final run does not fail mid-pipeline.

  1. Compute Pearson correlation between the two cyclical components
  2. Round result to 5 decimal places
  3. Prefer one reproducible Python script for the full pipeline: inspect workbooks, extract both nominal series, annualize 2024 from quarters, merge by year with CPI, deflate, log, HP-filter, correlate, write /root/answer.txt, then read it back

11a. Keep all transformations in that same script so extraction, deflation, detrending, correlation, and file output can be rerun together after any parsing fix; avoid patching results manually in separate steps.

11b. Keep the script modular even if it is a single file: separate workbook inspection, per-workbook extraction, optional latest-year aggregation, CPI alignment, and final analysis so diagnostics can show exactly where a year-range or quarter-capture mistake occurs.

11c. Keep the script parameterized around the latest-year decision: completed-annual-only and quarterly-derived-latest-year are both acceptable when supported by the prompt/workbook, but the run must execute one choice consistently from extraction through final reported sample span.

  1. Before concluding, rerun the final script end-to-end without error, explicitly print the extracted 2024 quarter labels/values and quarter counts for both series, the overlap year range/count, the final correlation, and read back /root/answer.txt to confirm the saved value was freshly written and matches the computed value

12a. If any prior run raised a parsing/alignment error or if the visible output was truncated before the final correlation/file confirmation, do at least one fresh rerun that visibly reaches the end; do not infer success from a partially shown earlier run.

12b. Treat the task as unfinished unless the observable final run shows all of: no exception, final correlation printed, /root/answer.txt written, and the read-back value matching the printed correlation.

12c. If diagnostics show a suspicious latest-year result (for example averaged 1 quarter, missing expected quarter labels, or a final span that contradicts the intended sample), STOP and debug extraction before accepting any printed correlation or answer file; a numerically plausible result does not override anomalous coverage diagnostics.

12d. In that final visible run, also print a one-line method summary matching the task request, e.g. Method used: annual sample years ..., nominal->real via CPI, log, HP(100), Pearson correlation; if the printed method does not match the prompt, fix the workflow before saving the answer.

HP Filter

Validation Checks

Validation Checks

Output Format

Single number to /root/answer.txt

Only use this output format when the task explicitly asks for a single numeric result saved there; otherwise, match the prompt's requested deliverable.

Only trust that file after an observable successful run shows the final correlation and a matching read-back from /root/answer.txt.

Before trusting /root/answer.txt, verify the computation ran end-to-end: confirm deflation, HP filtering, and correlation steps executed successfully and the script exited normally. If output is truncated or diagnostics stop early, rerun or inspect the error instead of treating an existing answer file as success.

Do not present the number as final unless the immediately preceding observable run printed the correlation and showed a matching read-back from a freshly written /root/answer.txt; if the environment also requires a fixed completion string or termination format, emit that exact required final signal after verification.

Tips

Economic Time Series Detrending and Correlation

Execution Protocol

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.