Modular AI Risk Intelligence Infrastructure for Financial Incident Analytics, Governance, Compliance, and Regulatory Decision-Making
AI-powered ecosystem for semantic analytics, operational risk intelligence, interactive dashboards, APIs, and LLM-driven insights.
Institution:** Pontifical Catholic University of SΓ£o Paulo (PUC-SP) β FACEI
Bachelorβs Program: Humanistic AI & Data Science β’ 5th Semester β’ 2026
Course: AI Security, Cybersecurity & Social Engineering
Professors β¨ Carlos Eduardo Paes and β¨ Eduardo Savino Gomes
Author: Fabiana β‘οΈ Campanari
AI.Incidents.in.Financial.Services.-.Demo.Video.mp4
Warning
The focus is on applied, hands-on learning with real datasets in AI governance and security contexts.
All sensitive content remains protected in private repositories when required.
Tip
This repository is part of a broader academic and technical ecosystem dedicated to Cybersecurity, Social Engineering, Artificial Intelligence Security, Financial Risk Intelligence, and Human-Centered Technology.
The project explores AI incident analysis, operational risk monitoring, governance frameworks, compliance intelligence, semantic analytics, and regulatory-oriented AI infrastructures for banking, financial services, and fintech environments.
Explore the central repository containing complementary materials, technical documentation, analyses, and related projects:
π Cybersecurity, Social Engineering & AI Security β Hub Repository
β¨ Part of the Human-Centered AI & Data Science Modeling Series
Integrating cybersecurity, artificial intelligence, financial risk analytics, data science, and human perspective through applied research and intelligent systems.
This project consolidates an end-to-end perspective on AI incidents in financial services, connecting public data from the AI Incident Database (AIID) to a complete pipeline of analysis, modeling, and exposure via API and dashboard.
From an executive perspective, the work demonstrates how dispersed incidents can be transformed into structured risk indicators, with a focus on algorithmic bias, operational risk, and governance responses. The main contribution lies in the integrated analytical architecture: from data acquisition to the availability of RESTful endpoints and a visualization layer.
β The system answers questions such as:
- Which types of AI applications generate the most incidents in the financial sector (credit, fraud detection, customer service, algorithmic trading, etc.)?
- Does algorithmic bias affect customer segments unevenly (income level, region, gender, vulnerable groups)?
- Is it possible to predict incident severity before a regulatory investigation, based on case attributes and model usage context?
- Which categories of operational risk are most associated with AI incidents in banks, insurers, and fintechs (fraud, process failures, IT issues, outsourcing)?
- How do incident frequency and types evolve over time, and do they concentrate in specific institutions or regulatory jurisdictions?
- What governance patterns appear in incident responses (model suspension, policy review, regulator notification, fines)?
- Are there early warning indicators in incident data that correlate with higher exposure to operational losses or reputational risk?
- To what extent do incidents involving generative AI differ from those involving traditional machine learning models in the financial context?
- How can AI risk metrics be integrated into existing frameworks for operational risk management, cybersecurity, and compliance in the financial sector?
- What transparency and incident reporting gaps still exist, and how can structured monitoring support regulators and risk teams?
Important
Correct positioning: predictive models should be treated as a methodological proof of concept. The main deliverable is the integrated analytical architecture β not a high-accuracy classifier ready for production.
- Introduction
- Objectives and Research Questions
- Theoretical Foundation and Data Context
- CRISP-DM Methodology
- Data Sources and Preparation
- Analytical Variables and Hypotheses
- Statistical Analysis and Inferential Results
- Machine Learning Modeling
- Relational Database and RESTful API
- Interactive Dashboard
- System Architecture
- Technical Notebook Structure
- Consolidated Results
- Limitations and Methodological Considerations
- Technology Stack
- Local Execution Guide
- Groq API Configuration
- Production Deployment
- Infrastructure and API Deployment on Render
- Project Structure
- Dependencies
- General Data Analysis and Machine Learning Modeling
- Conclusions and Future Work
- Acknowledgements
- References
1. Introduction
The use of Artificial Intelligence systems in the financial sector has been growing rapidly in applications such as credit scoring, fraud detection, algorithmic trading, *risk assessment, customer service automation, and compliance support. This advancement expands institutionsβ operational capacity but also introduces new risk vectors, especially in highly regulated environments sensitive to automated decision-making failures.
In the financial sector, AI failures do not only affect technical performance. They can generate reputational damage, discriminatory bias, operational losses, regulatory scrutiny, and changes in internal policies. Therefore, analyzing real AI incidents in this domain is a concrete way to bridge algorithmic governance, risk management, and empirical evidence.
This project was built using real documented incidents from the AI Incident Database (AIID) filtered for the financial services context. The central proposal is to transform this dataset into a structured analytical base capable of supporting statistical analysis, predictive modeling, relational storage, API exposure, and dashboard consumption.
1.2 Research problem
Given a set of AI incidents recorded across multiple sectors and filtered to the financial domain, the central problem is to evaluate whether:
- there are systematic patterns of bias and risk associated with certain types of AI applications (credit, fraud, trading); - certain customer segments are disproportionately affected; - governance and regulatory responses adequately match the severity of incidents.
| Stakeholder | Direct Benefit |
|---|---|
| Banks and Fintechs | Improve operational and reputational risk management |
| Regulators | Evidence-based and data-driven supervision |
| Risk Managers | Tools to assess exposure to AI incidents |
| Compliance | Identify regulatory gaps and prioritize audits |
| Investors | Understand the impact of AI incidents on institutional value |
Tip
For AI governance, the project illustrates how incident data can be transformed into indicators, predictive models, and APIs, enabling continuous monitoring and structured responses to risks.
To evaluate, based on structured data from AI incidents in the financial sector, whether there are relevant patterns of algorithmic bias, operational risk, and governance, producing evidence useful for analysis, monitoring, and decision support.
1. Identify AI incidents related to financial services.
2. Structure and enrich the data with derived analytical variables.
3. Evaluate statistical hypotheses on concentration, bias, severity, and regulatory response.
4. Build predictive models for severity classification and regulatory investigation.
5. Organize results into an architecture composed of notebooks, relational database, RESTful API, and dashboard.
| Hypothesis | Question | Approach |
|---|---|---|
| H1 | Are incidents concentrated in certain application types? | Chi-square goodness-of-fit |
| H2 | Does algorithmic bias disproportionately affect segments? | Chi-square test of independence |
| H3 | Do more severe incidents generate greater regulatory response? | Chi-square and logistic regression |
| H4 | Is there a temporal trend in incident volume? | Time correlation and trend analysis |
β Adopted significance level: Ξ± = 0.05 in all tests.
The project uses the AI Incident Database (AIID) as its main data source, a repository of real incidents involving AI systems, documented from public sources β maintained by the Responsible AI Collaborative and licensed under CC BY-SA 4.0.
| Access mode | Address | Usage |
|---|---|---|
| Official portal | https://incidentdatabase.ai/ |
Navigation and context |
| GraphQL API | https://incidentdatabase.ai/api/graphql |
Programmatic data collection (Notebook 1) |
| Kaggle dataset | kaggle datasets download konradb/ai-incident-database |
Offline fallback |
Important
Notebook 1 implements a 4-layer fallback strategy: GraphQL API β JSON cache β CSV cache β local incidents.csv. This ensures reproducibility even without internet access.
The project applies thematic filtering using more than 30 keywords across the title and description fields, targeting incidents related to:
- credit, loans, mortgages, and credit scoring;
- fraud, AML, and money laundering;
- banks, fintechs, and payments;
- algorithmic trading and financial markets;
- insurance and automated underwriting;
- risk and asset management;
- robo-advisors.
| Limitation | Impact | Adopted strategy |
|---|---|---|
| Only publicly reported incidents | Underrepresentation of true total | Treat as a biased sample |
| Geographic bias (US and EU dominance) | Limited generalizability | Restrict conclusions to scope |
| Financial values rarely complete | Severity proxy via text only | Use keywords as indicators |
| Heterogeneous text quality | Noisy derived variables | Conservative heuristics |
Important
These limitations do not invalidate the project, but require careful interpretation and moderation in conclusions.
The Flash Crash of May 6, 2010 is one of the most emblematic examples of operational risk and market risk associated with automation in financial environments. At 2:32 PM New York time, the U.S. stock market experienced a sudden drop that, in approximately 36 minutes, temporarily erased more than US$ 1 trillion in market value.
During this interval, the Dow Jones Industrial Average fell by more than 1,000 points, and some stocks briefly traded at extreme levels β in certain cases dropping from tens of dollars to just one cent β before rapidly returning to near-normal levels. The event demonstrated how highly automated markets can amplify disturbances at a systemic scale.
Regulatory analyses of the case indicate that one of the main triggers was the automated execution of a large sell order involving 75,000 E-mini S&P 500 contracts (electronic futures contracts that allow trading the S&P 500 index β an indicator of the 500 largest U.S. companies β with leverage), estimated at around US$ 4.1 billion. The algorithm executed orders based on a fraction of the trading volume in the previous minute, without incorporating sufficient guardrails (protective mechanisms such as price, time, or volatility limits).
This configuration contributed to a chain reaction among high-frequency trading algorithms (High-Frequency Trading β HFT: automated systems that execute thousands of trades per second), which began trading contracts among themselves, amplifying volatility and temporarily degrading liquidity. As a consequence, containment mechanisms such as circuit breakers (automatic trading halts triggered during extreme volatility) were activated to interrupt trading and stabilize the market.
- Regulatory investigation: the SEC (Securities and Exchange Commission β U.S. securities regulator) and the CFTC (Commodity Futures Trading Commission β U.S. derivatives regulator) conducted a joint formal investigation
- Policy changes: mandatory review of algorithmic trading systems and risk controls
- Strengthening of circuit breakers: implementation of more robust automatic interruption mechanisms
- Legal actions: prosecution against the trader responsible for the initial order
Within the analytical framework developed, the Flash Crash exemplifies the derived variables implemented:
application_type: algorithmic_tradingβ automated trading algorithmsincident_type: market_disruptionβ systemic market disturbanceseverity_level: criticalβ systemic, multi-billion-dollar short-term impactregulatory_investigation: 1β formal SEC and CFTC investigationpolicy_change: 1β mandatory review of trading systems
Important
This incident demonstrates how automated decision systems can generate billion-dollar operational losses within minutes, trigger severe regulatory investigations, and lead to mandatory institutional control revisions β validating the need for robust analytical architectures for monitoring, governance, and algorithmic risk management in critical financial environments.
The project was structured according to the CRISP-DM (Cross-Industry Standard Process for Data Mining) methodology, which organizes the analytical lifecycle into six iterative phases.
4.1 Applied Stages
| CRISP-DM Phase | Implementation in the project | Notebook |
|---|---|---|
| Business Understanding | Definition of the problem, objectives, and hypotheses | (README) |
| Data Understanding | Initial exploration, quality, and analytical potential | Notebook 1 |
| Data Preparation | Filtering, cleaning, derived features, SQLite | Notebook 1 |
| Modeling | Encoding, targets, training, and model evaluation | Notebook 3 |
| Evaluation | H1βH4 tests, statistical interpretation | Notebook 2 |
| Deployment | Flask RESTful API, Streamlit dashboard | Notebook 4 + dashboard/app.py |
4.2 Pipeline Flow
flowchart TD
A[AI Incident Database / Kaggle / Local Cache] --> B[Notebook 1 <br> <br> Exploration and Preparation]
B --> C[Treated CSV\nincidents_finance_filtered.csv]
B --> D[(SQLite\nai_finance_incidents.db)]
C --> E[Notebook 2 <br> <br> Statistics\nH1 to H4]
C --> F[Notebook 3 <br> <br> ML\nLR + RF + XGBoost]
F --> G[models/*.pkl]
D --> H[Notebook 4 <br> <br> Flask API\n9 endpoints]
G --> H
H --> I[Streamlit Dashboard\ndashboard/app.py]
Rule of thumb: always run the notebooks in the order 1 β 2 β 3 β 4. Running out of order will cause file not found errors.
5.1 Analytical Base
The processed base used in the analyses contains 31 incidents from the financial sector, covering the period from 2003 to 2023. This subset was treated as the main dataset for statistics and modeling.
| Field | Origin | Use |
|---|---|---|
incident_id |
Original | Primary key |
title |
Original | Filter and features |
text |
Derived (title + description) | Base of all derived variables |
year |
Derived from date |
Temporal analysis (H4) |
application_type |
Feature engineered | H1, ML |
incident_type |
Feature engineered | H2, ML |
customer_segment |
Feature engineered | H2, ML |
severity_level |
Feature engineered | H3, ML target |
regulatory_investigation |
Feature engineered | H3, ML target |
fine_imposed |
Feature engineered | ML feature |
policy_change |
Feature engineered | ML feature |
third_party_audit |
Feature engineered | ML feature |
- Standardization of column names to
snake_case - Conversion of dates β
datetime+ extraction ofyear - Creation of the
textfield =title + " " + description(lowercase) - Removal of duplicates by
incident_id - Thematic filtering by financial keywords
- Feature engineering
8 derived variables - Saving the
incidents_finance_filtered.csv - Creation and population of the SQLite database (3 tables)
Although the official AIID API is useful for acquisition and updates, the analytical stage depends heavily on the semantic quality of the textual fields. The project adopts the treated and enriched CSV as the main source for the subsequent stages, offering greater consistency and reproducibility.
The variables were constructed by heuristic inference on free text, using the consolidated text field. This approach is deterministic, explicit, and reproducible < although it depends on the semantic density of the textual fields.
| Variable | Type | Analytical Purpose |
|---|---|---|
application_type |
Categorical (7 classes) | Type of financial AI application |
incident_type |
Categorical (6 classes) | Nature of the incident |
customer_segment |
Categorical (5 classes) | Affected customer group |
severity_level |
Ordinal (4 levels) | Severity of the incident |
regulatory_investigation |
Binary | Formal regulatory investigation |
fine_imposed |
Binary | Fine or sanction applied |
policy_change |
Binary | Policy or system change |
third_party_audit |
Binary | Independent audit conducted |
The "semantic correlation" in the project was implemented as a match by keywords and textual radicals
not with embeddings, TF-IDF, or advanced NLP. Each incident receives the class of the first compatible set found in the text, with fallback categories when there is not enough evidence.
application_type
keyword examples:
credit_scoring: credit scor, loan, lending, mortgagefraud_detection: fraud, aml, anti-money launderingalgorithmic_trading: trading, high-frequency, flash crashrisk_assessment: underwriting, insurance, risk assessment
incident_type
keyword examples:
-
algorithmic_bias: bias, discriminat, racial, unfair, disparate impact -
operational_failure: crash, failure, outage, bug, error -
market_disruption: flash crash, volatility, circuit breaker -
data_breach: breach, leak, hack, privacy violation
severity_level
gradual impact logic:
critical: bankrupt, systemic, shutdown, billion, flash crash, tens of thousandshigh: investigation, lawsuit, fine, penalty, significant loss, deepfakemedium: complaint, concern, review, criticized, allegedlow: absence of the signs above
Governance Flags
specific keywords:
regulatory_investigation: investigation, inquiry, probe, sec, regulatorfine_imposed: fine, penalty, sanction, settlementpolicy_change: policy change, suspended, discontinued, haltedthird_party_audit: audit, independent review, third-party
This inference is an interpretable and reproducible heuristic, not deep semantic understanding. When title or description are poor or incomplete, the quality of derived variables weakens. Among the recommended next steps is to evolve to embeddings (FinBERT) and TF-IDF at the corpus scale.
Notebook 2 implements the Evaluation phase with descriptive statistics, bivariate analysis, and hypothesis testing on the 31 incidents from the 2003β2023 period.
- Test: Chi-square goodness of fit (uniform distribution as Hβ)
- Managerial interpretation: Rejection of uniformity identifies where governance must be more intensive (credit, fraud, algorithmic trading)
- Test: Chi-square test of independence
- Relevance: Connects AI ethics with operational and reputational risk; unequally affected segments can generate regulatory scrutiny and lawsuits
- Tests: Chi-square test of association + Logistic Regression (Odds Ratio)
- Complement: The logistic regression studies the relationship between incident attributes and the probability of regulatory investigation
- Tests: Spearman Correlation + Linear Regression (OLS)
- Caution: With a small base and short series, robust temporal patterns require more data
The most valuable contribution of Notebook 2 is not in "proving" hypotheses, but in organizing the analytical reasoning in a rigorous way. Even with limited statistical power, the notebook provides a coherent evaluation structure for the distribution of incidents, asymmetry between segments, the severity-governance relationship, and temporal evolution
supporting the empirical evidence layer of the project.
Notebook 3 implements the Modeling phase, developing supervised models for two tasks.
8.1 Modeling Dataset
| Attribute | Value |
|---|---|
| Total incidents | 31 |
| Initial features | 19 |
| Features after encoding | 14 |
| Missing values | None |
β Model 1
Binary Severity (severity_binary):
β Model 2
Regulatory Investigation (regulatory_investigation):
This distribution is the central methodological problem of the project.
| Algorithm | Role |
|---|---|
| Logistic Regression | Interpretable linear baseline |
| Random Forest | Tree ensemble, robust to noise |
| XGBoost | High-performance gradient boosting |
8.4 Reported Results
| Model | Algorithm | F1-Score | ROC-AUC |
|---|---|---|---|
| Severity | XGBoost | 0.0000 | 0.0833 |
| Investigation | XGBoost | 0.0000 | NaN |
These results show that the modeling, in its current form, has not achieved reliable predictive performance. The correct reading is:
- the ML pipeline was implemented correctly;
- feature engineering and serialization of the artifacts were performed;
- the base is too small and heavily imbalanced for robust generalization;
- the models should be treated as a proof of concept, not as a mature predictive solution.
Notebook 3 has academic value because it demonstrates: data preparation for ML, encoding, defining targets, comparing algorithms, evaluating with metrics, and serializing for integration with the API
fulfilling the Modeling phase of CRISP-DM in a didactic and traceable manner.
Notebook 4 implements the Deployment phase, creating a Flask API to expose data and models.
-- 3 related tables (minimum briefing requirement)
CREATE TABLE incidents (
incident_id INTEGER PRIMARY KEY,
title TEXT, summary TEXT,
occurred_date DATE, year INTEGER,
application_type TEXT, customer_segment TEXT,
incident_type TEXT, severity_level TEXT, text TEXT
);
CREATE TABLE financial_impacts (
impact_id INTEGER PRIMARY KEY AUTOINCREMENT,
incident_id INTEGER NOT NULL,
severity_level TEXT, estimated_loss TEXT, impact_description TEXT,
FOREIGN KEY (incident_id) REFERENCES incidents(incident_id)
);
CREATE TABLE regulatory_responses (
response_id INTEGER PRIMARY KEY AUTOINCREMENT,
incident_id INTEGER NOT NULL,
regulatory_investigation INTEGER DEFAULT 0,
fine_imposed INTEGER DEFAULT 0,
policy_change INTEGER DEFAULT 0,
third_party_audit INTEGER DEFAULT 0,
FOREIGN KEY (incident_id) REFERENCES incidents(incident_id)
);Base URL: http://localhost:5000 (local) or Render URL (production)
| Group | Method | Route | Description |
|---|---|---|---|
| Documentation | GET | / |
Status and list of endpoints |
| Data | GET | /api/incidents |
List with filters (application_type, severity_level, year, limit) |
| Data | GET | /api/incidents/<id> |
Detail + financial impact + regulatory response |
| Statistics | GET | /api/stats/by-application |
Concentration by application type |
| Statistics | GET | /api/stats/by-segment |
Incidents and bias rate by segment |
| Statistics | GET | /api/stats/temporal |
Time series by year |
| Statistics | GET | /api/stats/governance |
Frequency of governance flags |
| Predictions | POST | /api/predict/severity |
Classifies as high/low severity |
| Predictions | POST | /api/predict/investigation |
Probability of regulatory investigation |
9.3 Usage Example
# [List filtered incidents]()
curl "http://localhost:5000/api/incidents?application_type=credit_scoring&limit=10"
# [Severity prediction]()
curl -X POST http://localhost:5000/api/predict/severity \
-H "Content-Type: application/json" \
-d '{
"application_type": "credit_scoring",
"incident_type": "algorithmic_bias",
"customer_segment": "retail",
"year": 2024,
"fine_imposed": 0,
"policy_change": 0,
"third_party_audit": 0
}'
# [Expected response:]()
# [{"prediction": "high", "probability": 0.78, "confidence": "high",]()
# ["interpretation": "Severity: HIGH | confidence: high"}]()The prepare_model_input function ensures three critical points:
- Replicates the training transformation pipeline: applies
get_dummieswith the same categories - Creates missing columns with a value of 0: avoids
shape mismatcherrors - Orders columns in the same sequence as training: ensures correct alignment with the model's coefficients
The predictive endpoints are technically functional, but they depend on models with F1 = 0. They should be interpreted as a demonstration of integration, not as a reliable decision mechanism.
10.1 Overview
The dashboard (dashboard/app.py, built with Streamlit) is the visual consumption layer of the project. It consumes the Flask API via HTTP
it does not read files directly
respecting the separation of concerns in the architecture.
# [Automatic API URL resolution:]()
# [1. st.secrets["API_BASE_URL"] β Streamlit Cloud]()
# [2. os.environ["API_BASE_URL"] β Local .env]()
# [3. "http://localhost:5000" β Standard fallback]()When the API is offline, the dashboard loads the local CSV as an automatic fallback it never breaks during the demonstration.
10.2 Implemented Pages
| Page | Content |
|---|---|
| π Overview | 5 dynamic KPI cards Β· distribution by application Β· severity donut Β· time series Β· governance bars |
| π Explorer | Table filtered by application/severity/type/year Β· CSV download |
| π Statistical Analysis | Complete H1βH4 with scipy calculations Β· result badges Β· correlation heatmap |
| π€ ML Models | Algorithm comparison Β· Feature Importance Β· ROC curves Β· confusion matrix |
| π API Explorer | Live status Β· endpoint selector Β· parameters Β· JSON response |
| π― Risk Predictor | Form β prediction M1 (severity) + M2 (investigation) β probability gauges |
| π¬ AI Assistant | Groq llama-3.1-8b-instant + contextualized offline responses Β· history Β· suggestions |
The chatbot was migrated from OpenAI to Groq (llama-3.1-8b-instant):
| Criterion | OpenAI (before) | Groq (now) |
|---|---|---|
| Cost | ~$0.15/1M tokens | Free |
| Speed | ~40 tok/s | ~270 tok/s |
| Required SDK | openai |
Only requests |
| Configuration | Manual via UI | Automatic (secrets β env β UI) |
| Fallback | Offline mode | Offline mode + automatic retry |
β Key resolution logic (without changing code between environments):
def _get_groq_key() -> str:
try: return st.secrets["GROQ_API_KEY"] # 1. Streamlit Cloud
except: pass
env = os.environ.get("GROQ_API_KEY", "")
if env: return env # 2. Environment variable
return st.session_state.get("groq_key_manual", "") # 3. Manual input10.4 UI/UX Features
- Dark/Light mode with toggle in the sidebar
- KPI cards with values, icons, and deltas
- Plotly Charts fully interactive
- CSV Download filtered
- API Status in real-time (badge in the sidebar)
- Automatic Fallback
works without API and without Groq key
%%{init: {'theme':'dark'}}%%
flowchart LR
subgraph L1["Source Layer"]
A1["External AI Incident DB"]
A2["Kaggle Dataset"]
end
subgraph L2["Data Preparation Layer"]
B1["Notebook 1\nIngestion & Cleaning"]
B2["Feature Engineering"]
B3["Validated Analytical CSV"]
end
subgraph L3["Analytical & Modeling Layer"]
C1["Notebook 2\nStatistical Analysis"]
C2["Notebook 3\nML Training"]
C3["Model Evaluation"]
end
subgraph L4["Storage & Governance Layer"]
D1[("SQLite Analytical Store")]
D2[("Model Registry")]
D3["GitHub Repository\nVersion Control"]
end
subgraph L5["Deployment & Orchestration Layer"]
E1["Render Deployment Pipeline"]
E2["Streamlit Cloud Deployment"]
end
subgraph L6["Serving & Inference Layer"]
F1["Flask REST API\nPrediction Endpoints"]
F2["Public HTTPS Interface"]
F3["Groq API\nllama-3.1-8b-instant"]
end
subgraph L7["Consumption & Experience Layer"]
G1["Executive Dashboard"]
G2["Risk Scoring Interface"]
G3["AI Assistant for Analysis"]
end
subgraph L8["Stakeholder Layer"]
H1["Researchers & Academics"]
H2["Risk / Compliance Teams"]
H3["Decision Makers & Reviewers"]
end
A1 --> B1
A2 --> B1
B1 --> B2
B2 --> B3
B3 --> C1
B3 --> C2
B3 --> D1
C2 --> C3
C3 --> D2
B1 --> D3
C1 --> D3
C2 --> D3
D1 --> F1
D2 --> F1
D3 --> E1
D3 --> E2
E1 --> F1
F1 --> F2
F2 --> G1
F2 --> G2
F2 --> G3
F3 --> G3
E2 --> G1
G1 --> H1
G1 --> H2
G2 --> H2
G3 --> H1
G3 --> H3
%% STYLE
classDef node fill:#0d1117,stroke:#00d1c1,stroke-width:1.6px,color:#ffffff;
classDef db fill:#0d1117,stroke:#00d1c1,stroke-width:2.4px,color:#ffffff;
classDef cloud fill:#0d1117,stroke:#00d1c1,stroke-width:1.9px,color:#ffffff;
classDef layer fill:#111827,stroke:#00d1c1,stroke-width:1.4px,color:#ffffff;
class A1,A2,B1,B2,B3,C1,C2,C3,F1,F2,F3,G1,G2,G3,H1,H2,H3 node;
class D1,D2 db;
class D3,E1,E2 cloud;
class L1,L2,L3,L4,L5,L6,L7,L8 layer;
β Click here to view the diagram in higher resolution.
| Component | Current Technology | Recommended Evolution |
|---|---|---|
| Data Sources | AIID API, Kaggle CSV | Streaming with Kafka |
| Data Ingestion | pandas + requests | Airflow + dbt |
| Feature Store | Processed CSV | Feast / Tecton |
| Training Pipeline | Jupyter + scikit-learn | MLflow + Kubeflow |
| Model Registry | .pkl on disk | MLflow Registry |
| Data Warehouse | SQLite | PostgreSQL / BigQuery |
| Inference API | Flask | FastAPI + Gunicorn |
| Presentation Layer | Streamlit | Tableau / PowerBI |
11.3 Complete Data Flow
Ingestion β Processing β Feature Engineering β Training β Serialization
β Flask API (serving) β Streamlit Dashboard (consumption) β Groq (chatbot)
Why is
ai_finance_incidents.dbin the root? The database is accessed by the API (api/) and the notebooks (notebooks/). Keeping it in the root withos.path.abspatheliminates ambiguity in any OS.
Why
api/app_api.pyand notapp.pyin the root? To eliminate conflict withdashboard/app.py. Both were calledapp.py
distinct subfolder + name resolve this permanently.
CRISP-DM Phase: Data Understanding + Data Preparation
data/incidents_finance_filtered.csv β analytical base of all notebooks
ai_finance_incidents.db β database with 3 tables for the API
assets/distribuicao_variaveis.png β distributions dashboard
CRISP-DM Phase: Evaluation
Produces results of the H1βH4 tests and analytical visualizations.
CRISP-DM Phase: Modeling
models/severity_classifier.pkl β Serialized Model 1
models/investigation_classifier.pkl β Serialized Model 2
models/features_severity.pkl β Feature list for Model 1
models/features_investigation.pkl β Feature list for Model 2
CRISP-DM Phase: Deployment
api/app_api.py β Flask API ready for independent execution
| Deliverable | Status |
|---|---|
| Thematic base of financial incidents | β Solid |
| 8 derived variables with explicit logic | β Solid |
| Formalized H1βH4 hypothesis tests | β Solid |
| Complete and serialized ML pipeline | β Solid (technical) |
| Relational SQLite database with 3 tables | β Solid |
| RESTful API with 9 functional endpoints | β Solid |
| Dashboard with 7 interactive pages | β Solid |
| Groq chatbot with offline fallback | β Solid |
| Statement | Caution Needed |
|---|---|
| "The predictive models are ready for use" | β F1 = 0 indicates insufficient base |
| "XGBoost outperformed the other algorithms" | |
| "The results are generalizable" | |
| "The API can be used in production" |
The statistical analysis suggests a concentration of incidents in certain types of applications, signs of unequal exposure among customer segments in cases of algorithmic bias, and evidence of a misalignment between potential severity and formal governance response. In managerial terms, this reinforces that AI systems in financial services should be evaluated not only for technical performance but also for distributive impact, operational criticality, and institutional response capacity.
- Reduced base: only 31 incidents in the modeled scope
- Strong imbalance: 90.3% in a single severity class
- Only publicized incidents: underrepresentation of the real total
- Geographic bias: US and EU dominate the base
- Textual dependency: variable quality between incidents impacts the features
- Low statistical power for strong inferences in small scopes
- High sensitivity to a few extreme cases (e.g., Flash Crash distorts H4)
- Fragility of tests applied to subgroups with fewer than 5 observations
- Classes too rare to guarantee robust generalization
- High risk of overfitting with F1 = 0 in the final metrics
- Functional API without typical production controls:
- no authentication (JWT or API key)
- no structured logging
- no endpoint versioning (
/v1/) - no rate limiting
- no robust payload validation
| Library | Version | Use |
|---|---|---|
flask |
β₯ 2.3 | RESTful API |
flask-cors |
β₯ 4.0 | Cross-origin for the dashboard |
pandas |
β₯ 2.0 | Data manipulation |
numpy |
β₯ 1.24 | Numerical operations |
scipy |
β₯ 1.11 | Statistical tests (H1βH4) |
statsmodels |
β₯ 0.14 | Logistic regression, OLS |
scikit-learn |
β₯ 1.3 | Preprocessing and models |
xgboost |
β₯ 1.7 | Main model |
joblib |
β₯ 1.3 | Model serialization |
| Library | Version | Use |
|---|---|---|
streamlit |
β₯ 1.32 | Interactive dashboard |
plotly |
β₯ 5.18 | Interactive charts |
requests |
β₯ 2.31 | Calls to Flask and Groq API |
| Provider | Model | Cost | Integration |
|---|---|---|---|
| Groq (main) | llama-3.1-8b-instant | Free | REST via requests |
| Offline mode (fallback) | keywords | Zero | Local |
πΈΰΉ My Contacts Hub
ββββββββββββββ βΉπΰΉ ββββββββββββββ
β£β’β€ Back to Top
Copyright 2026 Quantum Software Development. Code released under the MIT license.