Skip to content

About

This project shows how to use Python + Ollama + Gemma for an FP&A analysis.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

AI-Assisted FP&A Revenue Intelligence

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.


1. Before you start

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.


2. First-time setup

You only need to do this once.

Step 1 — Download the project

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.


Step 2 — Install Python

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 --version

You should see a Python version.

For example:

Python 3.12.5

Step 3 — Install Ollama

Install Ollama for your operating system.

After installation, open a new terminal.

Check Ollama:

ollama --version

You should see an Ollama version.


Step 4 — Find the Gemma model name

Run:

ollama list

Look 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.


Step 5 — Select the Gemma model

Run:

ollama list

Find the exact name of the Gemma model.

For example:

gemma4:latest

Windows

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.

Windows PowerShell

You can also set the model before running the setup command:

$env:OLLAMA_MODEL="gemma4:latest"

Then run:

python setup.py

macOS or Linux

Run:

export OLLAMA_MODEL="gemma4:latest"

Then run:

python setup.py

Step 6 — Run setup

Open a terminal in the project folder.

Run:

python setup.py

The setup program checks:

  1. Python.
  2. Required Python packages.
  3. Ollama.
  4. 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.

3. Run the analysis

After setup is complete, run:

python run.py

The program will:

  1. Load the transaction data.
  2. Run the Python FP&A calculations.
  3. Identify material customer exceptions.
  4. Prepare a compact evidence package.
  5. Send the evidence to Ollama.
  6. Ask Gemma to interpret the results.
  7. Create the management review.
  8. Create an HTML management dashboard with Python-generated charts.
  9. Open the dashboard in your default browser.

You do not need to enter financial data manually.


4. Windows shortcut

Windows users can use the two batch files.

First-time setup

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.

Run the analysis

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.


5. Find the result

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.


6. What should you expect?

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.


7. If the AI analysis takes a long time

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.py

This 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.

7. If something goes wrong

Start with setup.

Run:

python setup.py

The setup program checks the most common problems.

Ollama is not found

Install Ollama.

Then close the terminal.

Open a new terminal.

Run:

python setup.py

again.

The Gemma model is not found

Run:

ollama list

Check 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.py

again.

The AI analysis does not run

Make sure Ollama is running.

If required, run:

ollama serve

Keep that terminal open.

Open a second terminal.

Run:

python run.py

8. What Python does

Python 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.


9. What Gemma does

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.


10. Data

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.


11. Why Python and AI are separate

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.


11. HTML management dashboard

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.

Management storytelling

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.

12. Project structure

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.


13. Quick start

If Python, Ollama and the Gemma model are already installed:

Step 1

Set the model name.

Step 2

Run:

python setup.py

Step 3

Run:

python run.py

Step 4

Open:

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.


14. Portfolio objective

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.

If Gemma takes a long time

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.

Testing, Issues & Design Decisions

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.

What these tests demonstrate

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.

Dashboard AI parsing

The dashboard accepts common Markdown heading formats and keeps valid Gemma prose if section labels are omitted.

About

This project shows how to use Python + Ollama + Gemma for an FP&A analysis.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages