This project shows how to use Python + Ollama + Gemma for an FP&A analysis.
Python does the finance. Gemma does the interpretation.
Python calculates the financial results.
Gemma reviews the results and writes a management interpretation.
You need:
- Windows, macOS, or Linux.
- Python 3.10 or later.
- Ollama.
- A Gemma model that is available in your Ollama installation.
You do not need:
- An OpenAI API key.
- A cloud AI account.
- Docker.
- A database.
The AI model runs locally through Ollama.
You only need to do this once.
Download or clone this repository.
Open the project folder.
For example:
C:\Projects\ai-fpa-revenue-intelligence
Do not rename the folders inside the project.
If Python is not installed, install Python 3.10 or later.
During Windows installation, select:
Add Python to PATH
After installation, open a new terminal.
Check Python:
python --versionYou should see a Python version.
For example:
Python 3.12.5
Install Ollama for your operating system.
After installation, open a new terminal.
Check Ollama:
ollama --versionYou should see an Ollama version.
Run:
ollama listLook for the Gemma model that you want to use.
If you have not downloaded one yet, download the Gemma model that you want to use.
For example:
ollama pull <your-gemma-model-tag>Replace the placeholder with the actual model tag.
Run:
ollama listFind the exact name of the Gemma model.
For example:
gemma4:latest
If you use setup_windows.bat, you do not need to set an environment variable first.
Double-click:
setup_windows.bat
The setup program asks for the model name if it is not already available in the terminal.
Enter the exact model name shown by ollama list.
You can also set the model before running the setup command:
$env:OLLAMA_MODEL="gemma4:latest"Then run:
python setup.pyRun:
export OLLAMA_MODEL="gemma4:latest"Then run:
python setup.pyOpen a terminal in the project folder.
Run:
python setup.pyThe setup program checks:
- Python.
- Required Python packages.
- Ollama.
- Your selected Gemma model.
If something is missing, the setup program tells you what to do.
When setup is successful, you will see:
Setup complete.
After setup is complete, run:
python run.pyThe program will:
- Load the transaction data.
- Run the Python FP&A calculations.
- Identify material customer exceptions.
- Prepare a compact evidence package.
- Send the evidence to Ollama.
- Ask Gemma to interpret the results.
- Create the management review.
- Create an HTML management dashboard with Python-generated charts.
- Open the dashboard in your default browser.
You do not need to enter financial data manually.
Windows users can use the two batch files.
Double-click:
setup_windows.bat
The setup file checks Python, installs the required Python packages, checks Ollama, and asks for the Gemma model if required.
Double-click:
run_windows.bat
If the Gemma model is not available in the current terminal session, the file asks for the model name.
For example:
Enter the exact Gemma model name: gemma4:latest
You do not need to set OLLAMA_MODEL manually when using the Windows batch files.
After the analysis finishes, open:
outputs/management_review.md
This is the main output.
It contains:
- Python financial results.
- Gemma's interpretation.
- Findings.
- Evidence.
- Risks.
- Recommended management actions.
The program also creates:
outputs/finance_results.json
This contains the structured financial evidence.
The program also creates:
outputs/ollama_prompt.txt
This shows the information and instructions sent to Gemma.
The company-level result should be similar to:
Forecast revenue: approximately £677,636
Actual revenue: approximately £676,812
Revenue variance: approximately -£824
Volume effect: approximately +£49,721
Price effect: approximately -£50,545
The key FP&A finding is:
Revenue is almost on forecast, but higher volume is being offset by lower average selling price.
Gemma then interprets this result and reviews the material customer exceptions.
The Gemma model can take time to load and generate a response. This is normal when the model runs locally.
The project now allows up to 15 minutes for the Ollama request. It also uses a streaming response, so a long generation does not fail just because the model needs more than a few minutes.
The AI input is intentionally compact. The current prompt is about 9 KB and contains only the company results, material customer exceptions, and relevant management context.
The project also limits the AI context window to 8,192 tokens by default. This keeps the local inference workload controlled.
If your computer is slow and the model needs more time, set a longer timeout before running the analysis.
Windows PowerShell example:
$env:OLLAMA_TIMEOUT_SECONDS="1800"
python run.pyThis allows up to 30 minutes.
You can also change the AI context size if required:
$env:OLLAMA_NUM_CTX="8192"You normally do not need to change this value.
Start with setup.
Run:
python setup.pyThe setup program checks the most common problems.
Install Ollama.
Then close the terminal.
Open a new terminal.
Run:
python setup.pyagain.
Run:
ollama listCheck the model name.
Then set OLLAMA_MODEL to the exact model name.
If the model is not installed, run:
ollama pull <your-gemma-model-tag>Then run:
python setup.pyagain.
Make sure Ollama is running.
If required, run:
ollama serveKeep that terminal open.
Open a second terminal.
Run:
python run.pyPython performs the financial analysis.
It calculates:
- Historical revenue.
- July 2011 forecast.
- Actual revenue.
- Revenue variance.
- Volume effect.
- Price effect.
- Customer exceptions.
- Risk classification.
The forecast uses:
- April: 20%
- May: 30%
- June: 50%
The calculations are deterministic.
The same input produces the same financial result.
Gemma does not calculate the financial results.
Gemma interprets the evidence produced by Python.
Gemma is asked to:
- Explain what happened.
- Identify the important drivers.
- Reconcile the financial evidence with management context.
- Identify business risks.
- Recommend management actions.
The requested output format is:
Finding
Evidence
Risk
Recommended management action
Gemma must not invent facts.
If there is no evidence for an explanation, Gemma should identify the missing evidence.
The transaction data is based on the UCI Online Retail II dataset.
This project uses a prepared January–July 2011 subset.
The original dataset is available from the UCI Machine Learning Repository.
The source dataset is licensed under CC BY 4.0. Citation: Chen, D. (2012). Online Retail II [Dataset]. UCI Machine Learning Repository. https://doi.org/10.24432/C5CG6D.
The management context is different.
The file:
context/management_context.csv
contains synthetic management scenarios.
These scenarios were created for this portfolio project.
They are not historical facts about the original retailer.
The project follows one simple rule:
Use Python for numbers. Use AI for judgement.
Python is used for:
- Calculations.
- Forecasting.
- Variance analysis.
- Reconciliation.
- Repeatable controls.
Gemma is used for:
- Interpretation.
- Summarisation.
- Connecting evidence.
- Explaining business implications.
- Drafting management recommendations.
This makes the workflow easier to understand and audit.
The main management output is outputs/management_dashboard.html.
It is generated by Python and is designed as a monthly FP&A management pack. It contains:
- Rounded management KPIs for revenue, variance, volume and ASP.
- Clean forecast versus actual revenue comparison.
- Revenue bridge showing volume and price effects.
- Revenue and volume trend views.
- Top 10 customer downside contributors and top 10 upside contributors.
- Customer, product and geography volume-driver analysis.
- AI management storytelling using Management Headline -> What Happened -> Why -> Business Implication -> Recommended Action.
- A customer contribution watchlist showing both downside and upside.
The dashboard is a normal HTML file. No Streamlit application or local web server is required. Plotly is embedded in the generated file. Exact financial values remain available in outputs/finance_results.json.
Gemma is instructed to avoid generic labels such as "marginal" or "significant" unless the evidence supports them. It must distinguish the headline revenue result from the underlying drivers. For example, revenue can be close to forecast while volume and ASP move materially in opposite directions.
The AI also receives deterministic driver evidence for customers, products, geography and the monthly volume trend. This allows it to discuss whether a volume increase is concentrated, broad-based or still requires validation without inventing a reason.
The Markdown output remains useful for audit, debugging and GitHub review.
ai-fpa-revenue-intelligence/
│
├── data/
│ └── selected_transactions_jan_jul_2011.csv
│
├── context/
│ └── management_context.csv
│
├── src/
│ ├── finance_engine.py
│ ├── ai_analysis.py
│ └── run_pipeline.py
│
├── outputs/
│
├── setup.py
├── setup_windows.bat
├── run.py
├── run_windows.bat
├── requirements.txt
└── README.md
You normally do not need to change the Python files.
If Python, Ollama and the Gemma model are already installed:
Set the model name.
Run:
python setup.pyRun:
python run.pyOpen:
outputs/management_dashboard.html
The dashboard opens automatically when the pipeline finishes.
The Markdown review is also available here:
outputs/management_review.md
That is all.
This project is not intended to show that AI can replace an FP&A analyst.
It demonstrates a practical use of AI:
Automate the repeatable financial analysis with Python.
Use AI to interpret the results and turn them into management insight.
The project uses a local LLM through Ollama.
This demonstrates a simple, reproducible and explainable AI-assisted FP&A workflow.
The Python finance analysis does not depend on Gemma. The dashboard is still created if the AI step fails.
The default Ollama settings are:
- Timeout: 15 minutes
- Context: 8,192 tokens
- Maximum AI output: 900 tokens
The AI prompt is intentionally compact. A prompt of about 17,000 characters is normally within the 8,192-token context window. A long local run is therefore more likely to be model loading or inference speed than a context-limit failure.
If the AI step fails, the dashboard shows the elapsed time and technical error. The Windows batch file also returns a failure status instead of incorrectly reporting the run as fully successful.
This project was tested iteratively. The issues below were found during actual execution of the workflow. They are documented because reliable AI-assisted FP&A requires controls around the model, the data, the operating environment and the presentation layer.
| Issue found | Root cause | Resolution | Lesson |
|---|---|---|---|
| Ollama returned no usable final answer | Gemma 4 could consume the output budget in its thinking process | Switched to the native Ollama chat API and explicitly disabled thinking for this use case. Added diagnostics for empty responses. | A successful model call is not the same as a usable AI result. |
| Windows batch file failed with an unexpected command error | The & character in the project title was interpreted by Windows CMD |
Escaped the special character in the batch files. | Test the actual user execution path, not only the Python script. |
| Selected Ollama model was not inherited when setup was launched by double-click | Environment variables from a PowerShell session are not automatically available to a separately launched batch process | Added a model prompt and fallback handling. | CLI and GUI execution paths can have different environment behaviour. |
| Dashboard reported AI output but assessment boxes were empty | The LLM response parser expected one exact heading format | Added tolerant parsing for numbered, Markdown, bold and inline headings, plus a prose fallback. | LLM output needs validation and robust parsing. |
| Volume chart labels were clipped | Static value labels reached the chart boundaries | Moved driver values to hover information. | Management charts should favour readability over decoration. |
| Four AI assessment columns became difficult to read | Long management narratives were forced into narrow vertical cards | Changed the assessment to horizontal full-width sections. | AI-generated text needs a presentation design that matches its content. |
AI narrative used $ for a GBP value |
Model wording did not consistently follow the supplied currency instruction | Added a presentation safeguard and reinforced GBP-only instructions in the prompt. | Financial outputs require domain-specific validation. |
| Customer values rounded to £K created misleading percentages | A small non-zero forecast could display as £0K while its percentage variance remained very large | Customer watchlist now shows full £ values and calculates percentages from unrounded values. | Never calculate or interpret financial percentages from rounded display values. |
| Customers with zero forecast showed misleading 0.0% variance | Percentage logic used a zero fallback when the denominator was zero | Display N/M when forecast is zero and actual revenue is positive, with a small legend. |
Zero-denominator financial metrics need explicit business rules. |
The project was not designed around the assumption that an LLM response, financial metric or dashboard rendering would always behave correctly on the first attempt. Testing exposed failure modes across AI inference, output parsing, Windows execution, financial presentation and visual design. Each issue resulted in a control, validation rule or design change.
The design therefore follows a simple principle:
Python produces the financial truth. AI interprets it. Validation controls the hand-off.
The dashboard accepts common Markdown heading formats and keeps valid Gemma prose if section labels are omitted.