|
1 | | -import pathlib |
2 | 1 | import pandas as pd |
| 2 | +import os |
3 | 3 |
|
4 | | -src = pathlib.Path("02-Matrices/risk_matrix.csv") |
5 | | -dst_dir = pathlib.Path("docs/reports") |
6 | | -dst_dir.mkdir(parents=True, exist_ok=True) |
7 | | -dst = dst_dir / "risk_matrix.xlsx" |
8 | | -pd.read_csv(src).to_excel(dst, index=False, sheet_name="RiskMatrix") |
9 | | -print(f"Wrote {dst}") |
| 4 | + |
| 5 | +def generate_risk_xlsx( |
| 6 | + csv_path: str = "02-Matrices/risk_matrix.csv", |
| 7 | + output_path: str = "docs/reports/risk_matrix.xlsx", |
| 8 | +) -> None: |
| 9 | + """ |
| 10 | + Reads the risk matrix CSV, calculates Risk (P*I), and exports the data to an Excel file. |
| 11 | + """ |
| 12 | + try: |
| 13 | + # 1. Read the CSV file |
| 14 | + df = pd.read_csv(csv_path, sep=",") |
| 15 | + |
| 16 | + # 2. Basic Data Cleaning (ensure proper types for calculation) |
| 17 | + df["Probability"] = pd.to_numeric(df["Probability"], errors="coerce") |
| 18 | + df["Impact"] = pd.to_numeric(df["Impact"], errors="coerce") |
| 19 | + |
| 20 | + # 3. Recalculate Risk |
| 21 | + df["Risk"] = df["Probability"] * df["Impact"] |
| 22 | + |
| 23 | + # 4. Sort the DataFrame by Risk (descending) and Impact (descending) |
| 24 | + df = df.sort_values(by=["Risk", "Impact"], ascending=[False, False]) |
| 25 | + |
| 26 | + # 5. Export to Excel |
| 27 | + output_dir = os.path.dirname(output_path) |
| 28 | + if not os.path.exists(output_dir): |
| 29 | + os.makedirs(output_dir) |
| 30 | + |
| 31 | + df.to_excel(output_path, index=False, sheet_name="Risk_Matrix") |
| 32 | + |
| 33 | + print(f"\nSUCCESS: Risk matrix processed and saved to: {output_path}") |
| 34 | + print(f" Total risks processed: {len(df)}") |
| 35 | + print(" Top 3 Risks (Score):") |
| 36 | + print(df[["ID", "Asset", "Risk"]].head(3).to_markdown(index=False)) |
| 37 | + |
| 38 | + except FileNotFoundError: |
| 39 | + print(f"ERROR: CSV file not found at {csv_path}. Please ensure the file exists.") |
| 40 | + except Exception as e: |
| 41 | + print(f"ERROR during Excel generation: {e}") |
| 42 | + |
| 43 | + |
| 44 | +if __name__ == "__main__": |
| 45 | + generate_risk_xlsx() |
0 commit comments