Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/andresshm/fini-marketing-intelligence/llms.txt

Use this file to discover all available pages before exploring further.

The strategic insights engine is a Python script that queries the enriched analytics views, computes four key marketing signals, and writes a human-readable Markdown report to reports/strategic_insights.md on every pipeline run. Rather than requiring an analyst to manually interpret dashboards, the engine quantifies the most important findings — which customer segments drive revenue, how promotions affect margins, which new product launched strongest, and which region lags the rest — and pairs each metric with a concrete recommendation. All four insights are derived from the same two PostgreSQL views: vw_sales_enriched for transactional data and vw_product_launches for new-product performance.

Data Sources

The script loads both views into pandas DataFrames at the start of every run:
sales = pd.read_sql("""
SELECT *
FROM vw_sales_enriched
""", engine)

launches = pd.read_sql("""
SELECT *
FROM vw_product_launches
""", engine)
vw_sales_enriched is a flat view joining fact_sales, dim_customers, and dim_products, making columns such as purchase_frequency, region, discount, units, revenue, and margin available without additional joins. vw_product_launches extends the sales data with launch_date and days_since_launch for every product, enabling first-90-day cohort analysis.

The Four Insight Categories

1

Customer Value

Groups revenue by the purchase_frequency dimension in vw_sales_enriched, identifies the top two frequency segments by total revenue, and calculates their combined share of overall revenue.
freq = (
    sales.groupby("purchase_frequency")["revenue"]
    .sum()
    .sort_values(ascending=False)
)

top_freq = freq.index[:2]

pct = (
    freq.loc[top_freq].sum()
    / freq.sum()
    * 100
)
Output example: The Medium and High frequency segments generate 79.6% of total revenue, confirming that retaining existing frequent buyers is more impactful than acquiring new low-frequency customers.
2

Promotions

Splits all transactions into two groups — discounted (discount > 0) and non-discounted (discount == 0) — then calculates the percentage change in average units sold and average margin between the two groups.
promo = sales.copy()

promo["promo_group"] = promo["discount"].apply(
    lambda x: "Discount" if x > 0 else "No Discount"
)

avg_units = (
    promo.groupby("promo_group")["units"]
    .mean()
)

avg_margin = (
    promo.groupby("promo_group")["margin"]
    .mean()
)

units_change = (
    (avg_units["Discount"] / avg_units["No Discount"] - 1)
    * 100
)

margin_change = (
    (avg_margin["Discount"] / avg_margin["No Discount"] - 1)
    * 100
)
Output example: Promotions increase average units sold by +49.8% while average margin changes by +6.0%, indicating that the volume uplift more than compensates for the discount — a net-positive result when applied selectively.
3

Product Launches

Filters vw_product_launches to the first 90 days post-launch, aggregates revenue by product, and identifies the single highest-revenue product in that window.
launch_top = (
    launches[launches["days_since_launch"] <= 90]
    .groupby("product_name")["revenue"]
    .sum()
    .sort_values(ascending=False)
)

top_product = launch_top.index[0]

top_revenue = launch_top.iloc[0]
Output example: Fruit Rings was the strongest launch, generating €11,730 in its first 90 days — making it the benchmark product whose marketing mix and distribution strategy should be studied and replicated.
4

Regional Performance

Groups revenue from vw_sales_enriched by region, identifies the lowest-performing region, and calculates its share of total revenue.
region = (
    sales.groupby("region")["revenue"]
    .sum()
    .sort_values()
)

lowest_region = region.index[0]

lowest_pct = (
    region.iloc[0]
    / region.sum()
    * 100
)
Output example: The South region accounts for only 18.7% of total revenue, the smallest share of any region — flagging it as a priority for targeted growth campaigns or distribution expansion.

Sample Report Output

Below is a real example of reports/strategic_insights.md produced by the engine from the current dataset:
# Strategic Insights Report

Generated: 2026-06-23 00:13:38.828354


## Customer Value

Los clientes Medium, High
generan el 79.6% del revenue total.

**Recomendación:**
Priorizar estrategias de fidelización y retención.


## Promotions

Las promociones incrementan las unidades vendidas
un 49.8%.

El margen medio cambia un 6.0%.

**Recomendación:**
Aplicar descuentos de forma selectiva,
priorizando productos estratégicos.


## Product Launches

Fruit Rings
ha sido el lanzamiento más exitoso,
generando 11,730 € durante
sus primeros 90 días.

**Recomendación:**
Analizar los factores de éxito para replicarlos.


## Regional Performance

La región South
representa únicamente el 18.7%
del revenue.

**Recomendación:**
Evaluar oportunidades de crecimiento
y campañas específicas.

Report Output

The engine writes the assembled insights to reports/strategic_insights.md using Python’s built-in file I/O:
report_dir = Path("reports")
report_dir.mkdir(exist_ok=True)

output = report_dir / "strategic_insights.md"

with open(output, "w", encoding="utf-8") as f:

    f.write("# Strategic Insights Report\n\n")

    f.write(f"Generated: {datetime.now()}\n\n")

    f.write("\n".join(insights))
The report directory is created automatically if it does not exist. Each section in the output file corresponds to one of the four insight categories above, with a plain-language finding and a concrete marketing recommendation.
The reports/strategic_insights.md file is overwritten on every pipeline run — it always reflects the most recently loaded data. Archive previous versions manually or via version control if you need a historical record of insight snapshots.
You can extend the insights engine by adding new insight blocks to the insights list. Any SQL query from the Analytics SQL Queries reference can be loaded as a pandas DataFrame and used to derive additional signals — for example, margin degradation by season or repeat-purchase rate by product category.

Build docs developers (and LLMs) love