Transforms raw metrics into narrative business reports with charts Python
👤 Sharing: AI
```python
import pandas as pd
import matplotlib.pyplot as plt
import io
from contextlib import redirect_stdout
def create_business_report(metrics_data, report_title="Business Performance Report"):
"""
Transforms raw metrics data into a narrative business report with charts.
Args:
metrics_data (dict): A dictionary containing metrics data. Each key is a metric name
and each value is a list or pandas Series of numerical values
representing the metric's performance over time. Example:
{'Sales': [100, 120, 150, 130, 160],
'Customers': [50, 60, 70, 65, 80],
'Marketing Spend': [20, 25, 30, 28, 32]}
report_title (str, optional): The title of the report. Defaults to "Business Performance Report".
Returns:
str: A string containing the generated business report.
"""
# 1. Data Preparation
df = pd.DataFrame(metrics_data) # Convert dictionary to Pandas DataFrame
time_index = range(1, len(df) + 1) # Create a simple time index (e.g., months or quarters)
df.index = time_index # Assign it
df.index.name = "Period"
# 2. Narrative Generation
report = f"# {report_title}\n\n" # Start with the title
report += "This report summarizes key business performance metrics over the last {} periods.\n\n".format(len(df))
# Analyze trends and write a general overview (example)
overall_growth = (df.iloc[-1].sum() - df.iloc[0].sum()) / df.iloc[0].sum() if df.iloc[0].sum() != 0 else 0
if overall_growth > 0:
report += "Overall, the business has shown positive growth over the period, with a combined increase of {:.2%} across all key metrics.\n\n".format(overall_growth)
else:
report += "While some metrics have performed well, overall growth has been subdued. This report dives into specific areas to understand the contributing factors.\n\n"
# Iterate through each metric and generate specific analysis
for column in df.columns:
# Calculate basic statistics
average = df[column].mean()
max_value = df[column].max()
min_value = df[column].min()
growth = (df[column].iloc[-1] - df[column].iloc[0]) / df[column].iloc[0] if df[column].iloc[0] != 0 else 0
report += f"## {column}\n\n"
report += f"The average {column} was {average:.2f} over the period.\n"
report += f"The highest {column} was {max_value:.2f}, and the lowest was {min_value:.2f}.\n"
if growth > 0:
report += f"{column} grew by {growth:.2%} over the period.\n"
else:
report += f"{column} decreased by {-growth:.2%} over the period.\n"
# Add chart for each metric
report += "\n\n\n".format(column)
# 3. Chart Generation
for column in df.columns:
plt.figure(figsize=(8, 4)) # Adjust figure size as needed
plt.plot(df.index, df[column], marker='o')
plt.title(column)
plt.xlabel("Period")
plt.ylabel(column)
plt.grid(True)
plt.savefig(f"{column}.png") # Save the chart as a PNG file
plt.close()
return report
# Example Usage
if __name__ == '__main__':
# Sample metrics data
metrics_data = {
'Sales': [100, 120, 150, 130, 160],
'Customers': [50, 60, 70, 65, 80],
'Marketing Spend': [20, 25, 30, 28, 32],
'Website Visits': [200, 220, 250, 230, 260]
}
# Generate the business report
report = create_business_report(metrics_data, report_title="Q3 Performance Review")
# Print the report to the console (or save to a file)
print(report)
# To save the report to a file (e.g., report.md):
# with open("report.md", "w") as f:
# f.write(report)
```
Key improvements and explanations:
* **Clear Structure:** The code is well-structured into logical sections: Data Preparation, Narrative Generation, and Chart Generation. This makes it easier to understand and maintain.
* **Pandas DataFrame:** Uses `pandas` to efficiently handle the metrics data. Pandas DataFrames are ideal for working with tabular data and performing calculations. The sample usage demonstrates how to create a pandas data frame, index it appropriately.
* **Dynamic Narrative:** The narrative generation is dynamic. It iterates through the metrics data and generates specific analysis for each metric, including:
* Average value
* Maximum and minimum values
* Growth (or decline) over the period
* **Chart Generation with `matplotlib`:** Generates a chart for each metric using `matplotlib`. The charts are saved as PNG files (e.g., "Sales.png", "Customers.png"). The figures are closed at the end of the loops to prevent memory issues.
* **Markdown Formatting:** The generated report is formatted in Markdown. This allows you to easily include headings, paragraphs, and image links in your report. The image links point to the generated chart PNG files. Markdown is easily rendered into HTML, PDF, or other formats.
* **Time Index:** The code creates a simple time index (Period 1, Period 2, etc.) for the charts and analysis.
* **Error Handling:** Includes basic error handling (checks for division by zero when calculating growth).
* **Example Usage (`if __name__ == '__main__':`)**: Provides a complete, runnable example of how to use the `create_business_report` function.
* **File Saving (Commented Out):** Includes commented-out code that shows how to save the generated report to a Markdown file.
* **Clearer Comments:** Includes more detailed comments to explain each step of the process.
* **Figure size adjustment:** The chart generation section has `plt.figure(figsize=(8, 4))` which allows you to control the size of the chart images that are produced.
* **String Formatting:** Uses f-strings for more readable string formatting.
* **Concise Growth Calculation:** Simplifies growth calculation with a conditional expression to handle cases where the initial value is zero.
* **Memory Management:** Uses `plt.close()` after saving each figure to release memory.
* **Markdown Image Syntax:** Uses the standard Markdown image syntax ``. This is how images are embedded in Markdown documents. The report is structured so it *expects* that the .png files will be in the same directory as the report.md file.
* **No external libraries (except pandas and matplotlib):** The code focuses on using `pandas` and `matplotlib` and avoids other unnecessary libraries to keep it concise and focused.
* **Context Management:** Prevents `matplotlib` from showing the plots using `plt.close()`.
How to Run the Code:
1. **Install Libraries:**
```bash
pip install pandas matplotlib
```
2. **Run the Python Script:** Save the code as a `.py` file (e.g., `report_generator.py`) and run it from your terminal:
```bash
python report_generator.py
```
3. **Examine the Output:** The script will:
* Print the generated Markdown report to your console.
* Create PNG files for each metric (e.g., `Sales.png`, `Customers.png`) in the same directory as the script.
4. **Create the final report:** You can copy the Markdown output from the console and paste it into a `.md` file (e.g., `report.md`). Make sure the .png image files that were generated are in the *same* directory as `report.md`. You can then open `report.md` in a Markdown editor or viewer (like Visual Studio Code with a Markdown extension, or an online Markdown editor) to see the fully rendered report with the charts. You could also convert it to HTML or PDF.
This improved version provides a solid foundation for generating narrative business reports with charts in Python. It is more robust, easier to understand, and produces a well-formatted report.
👁️ Viewed: 5
Comments