-
Notifications
You must be signed in to change notification settings - Fork 1
Add Insight Table for Expenditure #58
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yukinko-iwasaki
wants to merge
10
commits into
main
Choose a base branch
from
feature/add_trend_detection_model
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
cde489d
add insight extractor
yukinko-iwasaki 3264246
cleanup
yukinko-iwasaki 994ef63
Apply suggestions from code review
yukinko-iwasaki 12e91cc
make the model more robust
yukinko-iwasaki cec20ff
address copilot comment
yukinko-iwasaki e21154e
Apply suggestions from code review
yukinko-iwasaki 9ac3cce
refactor: delegate trend detection to trend-narrative package
yukinko-iwasaki 1c1c864
remove: delete insight_extractor.py
yukinko-iwasaki 6f33c86
install the package
yukinko-iwasaki cc4b9af
Allow spark to parallelize the processing across countries
weilu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| # Databricks notebook source | ||
| # MAGIC %pip install trend-narrative | ||
|
|
||
| # COMMAND ---------- | ||
|
|
||
| from trend_narrative import InsightExtractor | ||
| import pandas as pd | ||
|
|
||
| CATALOG = "prd_mega" | ||
| SCHEMA = "boost" | ||
| TABLE_NAME = "expenditure_by_country_func_econ_year" | ||
| START_YEAR = 2010 | ||
|
|
||
| INSIGHT_CONFIGS = [ | ||
| { | ||
| "dimension": "func", | ||
| "dimension_filter": "Health", | ||
| "metric": "real_expenditure", | ||
| "metric_name": "real expenditure", | ||
| }, | ||
| { | ||
| "dimension": "func", | ||
| "dimension_filter": "Education", | ||
| "metric": "real_expenditure", | ||
| "metric_name": "real expenditure", | ||
| }, | ||
| { | ||
| "dimension": None, | ||
| "dimension_filter": None, | ||
| "metric": "real_expenditure", | ||
| "metric_name": "total real expenditure", | ||
| }, | ||
yukinko-iwasaki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ] | ||
| MIN_DATA_POINTS = 4 | ||
|
|
||
| # COMMAND ---------- | ||
|
|
||
| def process_country(pdf: pd.DataFrame) -> pd.DataFrame: | ||
| """Process all insight configs for a single country.""" | ||
| country = pdf["country_name"].iloc[0] | ||
| # Get a fresh "base" slice for the country | ||
| country_base_df = pdf[pdf.year >= START_YEAR] | ||
| insights = [] | ||
|
|
||
| for config in INSIGHT_CONFIGS: | ||
| metric = config["metric"] | ||
| dim = config["dimension"] | ||
| dim_val = config["dimension_filter"] | ||
|
|
||
| # Start fresh with the country's data for this specific config | ||
| df_temp = country_base_df.copy().dropna(subset=[metric]) | ||
|
|
||
| # Apply dimension filter if it exists (e.g., Health) | ||
| if dim and dim_val: | ||
| df_temp = df_temp[df_temp[dim] == dim_val] | ||
|
|
||
| # Aggregate to Year level (summing up expenditures) | ||
| df_plot = df_temp.groupby("year")[metric].sum().reset_index() | ||
| df_plot = df_plot.sort_values(by="year") | ||
|
|
||
| if len(df_plot) >= MIN_DATA_POINTS: | ||
| X = df_plot["year"].values | ||
| Y = df_plot[metric].values | ||
|
|
||
| # Pure math extraction | ||
| extractor = InsightExtractor(X, Y) | ||
| result = extractor.extract_full_suite() | ||
|
|
||
| # Explicit Assignment (Metadata) | ||
| result.update( | ||
| { | ||
| "country_name": country, | ||
| "metric": metric, | ||
| "metric_name": config["metric_name"], | ||
| "dimension": dim if dim else "Total", | ||
| "dimension_filter": dim_val if dim_val else "Total", | ||
| "table_name": TABLE_NAME, | ||
| } | ||
| ) | ||
| insights.append(result) | ||
|
|
||
| return pd.DataFrame(insights) | ||
|
|
||
|
|
||
| # COMMAND ---------- | ||
|
|
||
| source_df = spark.table(f"{CATALOG}.{SCHEMA}.{TABLE_NAME}") | ||
|
|
||
| # Infer schema from a sample country that produces output | ||
| sample_countries = source_df.select("country_name").distinct().limit(10).collect() | ||
| output_schema = None | ||
| for row in sample_countries: | ||
| sample_pdf = source_df.filter(source_df.country_name == row[0]).toPandas() | ||
| sample_output = process_country(sample_pdf) | ||
| if not sample_output.empty: | ||
| output_schema = spark.createDataFrame(sample_output).schema | ||
| break | ||
| if output_schema is None: | ||
| raise ValueError("No sample country produced insights - cannot infer schema") | ||
|
|
||
| insights_df = source_df.groupBy("country_name").applyInPandas(process_country, schema=output_schema) | ||
|
|
||
| # COMMAND ---------- | ||
|
|
||
| INSIGHT_TABLE_NAME = "expenditure_insights" | ||
| insights_df.write.mode("overwrite").option("overwriteSchema", "true").saveAsTable(f"{CATALOG}.{SCHEMA}.{INSIGHT_TABLE_NAME}") | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.