Introduction
In this tutorial, you'll learn how to build a basic personal finance tracking application using Python and the OpenAI API. This tutorial is inspired by OpenAI's acquisition of Hiro Finance, a company that used AI to help people manage their personal finances. We'll create a simple application that can analyze spending patterns and provide basic financial insights using AI-powered natural language processing.
Prerequisites
Before starting this tutorial, you'll need:
- A computer with Python 3.7 or higher installed
- An OpenAI API key (free to get at platform.openai.com)
- Basic understanding of Python programming concepts
- Internet connection
Step-by-Step Instructions
1. Set up your development environment
First, create a new directory for your project and navigate to it:
mkdir finance_tracker
cd finance_tracker
Next, create a virtual environment to keep your project dependencies isolated:
python -m venv finance_env
source finance_env/bin/activate # On Windows: finance_env\Scripts\activate
This creates a clean environment for our project and prevents conflicts with other Python packages.
2. Install required packages
Install the necessary Python packages using pip:
pip install openai pandas
We're installing two packages: openai for accessing OpenAI's API and pandas for handling financial data.
3. Get your OpenAI API key
Visit platform.openai.com and create an account if you don't have one. Then, navigate to the API keys section and create a new secret key. Copy this key as you'll need it in the next step.
4. Create your main application file
Create a file called finance_tracker.py and add the following code:
import os
import openai
import pandas as pd
from datetime import datetime
# Set your OpenAI API key
openai.api_key = os.getenv('OPENAI_API_KEY')
# If you don't have an environment variable set, you can hardcode it here
# openai.api_key = 'your-api-key-here'
def analyze_spending(transactions):
"""Analyze spending patterns using OpenAI"""
# Create a simple transaction summary
df = pd.DataFrame(transactions)
total_spent = df['amount'].sum()
# Prepare prompt for OpenAI
prompt = f"""
Analyze these spending transactions and provide financial insights:
{df.to_string(index=False)}
Total amount spent: ${total_spent:.2f}
Please provide:
1. A summary of spending categories
2. Suggestions for improvement
3. A brief financial health assessment
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a personal finance assistant. Analyze spending patterns and provide helpful financial insights."},
{"role": "user", "content": prompt}
],
max_tokens=300,
temperature=0.5
)
return response['choices'][0]['message']['content']
except Exception as e:
return f"Error analyzing spending: {str(e)}"
# Sample transactions
sample_transactions = [
{'date': '2023-01-15', 'description': 'Grocery Store', 'amount': 85.30, 'category': 'Food'},
{'date': '2023-01-18', 'description': 'Gas Station', 'amount': 45.00, 'category': 'Transportation'},
{'date': '2023-01-20', 'description': 'Online Shopping', 'amount': 120.00, 'category': 'Entertainment'},
{'date': '2023-01-22', 'description': 'Restaurant', 'amount': 65.50, 'category': 'Food'},
{'date': '2023-01-25', 'description': 'Electricity Bill', 'amount': 95.25, 'category': 'Utilities'}
]
# Run analysis
if __name__ == "__main__":
print("Analyzing your spending patterns...")
result = analyze_spending(sample_transactions)
print(result)
5. Set up environment variables
Create a file called .env in your project directory and add your API key:
OPENAI_API_KEY=your_actual_api_key_here
Then modify your finance_tracker.py to load the environment variable:
import os
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Set your OpenAI API key
openai.api_key = os.getenv('OPENAI_API_KEY')
6. Install python-dotenv and test your application
Install the python-dotenv package to handle environment variables:
pip install python-dotenv
Now run your application:
python finance_tracker.py
You should see AI-generated insights about your spending patterns.
7. Extend the application
Let's add a function to save transaction data to a CSV file:
def save_transactions(transactions, filename="transactions.csv"):
"""Save transactions to CSV file"""
df = pd.DataFrame(transactions)
df.to_csv(filename, index=False)
print(f"Transactions saved to {filename}")
# Add this to your main function
save_transactions(sample_transactions)
8. Create a simple user interface
Add a simple input function to let users add their own transactions:
def get_user_transactions():
"""Get transactions from user input"""
transactions = []
print("Enter your transactions (press Enter with empty description to finish):")
while True:
description = input("Description: ")
if not description:
break
try:
amount = float(input("Amount: "))
category = input("Category (Food, Transportation, etc.): ")
transactions.append({
'date': datetime.now().strftime('%Y-%m-%d'),
'description': description,
'amount': amount,
'category': category
})
except ValueError:
print("Invalid amount. Please try again.")
return transactions
# Replace the sample_transactions with user input
# transactions = get_user_transactions()
# result = analyze_spending(transactions)
Summary
In this tutorial, you've learned how to create a basic personal finance tracking application using Python and OpenAI's API. You've built a system that can analyze spending patterns and provide AI-generated financial insights. This demonstrates how AI can be used to help people better understand and manage their personal finances.
The key concepts covered include:
- Setting up a Python development environment
- Using the OpenAI API for natural language processing
- Working with financial data using pandas
- Creating a simple user interface for data input
- Handling API keys securely with environment variables
This foundation can be expanded to include more sophisticated features like budget tracking, goal setting, or integration with real financial data sources.



