import csv
import json
from datetime import datetime
def export_transactions_csv(account_id, filename="transactions.csv"):
"""Export transactions to CSV file."""
client = MonzoClient()
transactions = client.transactions.list(account_id=account_id, limit=500)
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
fieldnames = [
'id', 'date', 'description', 'amount_gbp', 'category',
'merchant_name', 'merchant_category', 'notes'
]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for txn in transactions:
writer.writerow({
'id': txn.id,
'date': txn.created,
'description': txn.description,
'amount_gbp': txn.amount / 100,
'category': txn.category or '',
'merchant_name': txn.merchant.name if txn.merchant else '',
'merchant_category': txn.merchant.category if txn.merchant else '',
'notes': txn.notes or ''
})
print(f"Exported {len(transactions)} transactions to {filename}")
def export_transactions_json(account_id, filename="transactions.json"):
"""Export transactions to JSON file."""
client = MonzoClient()
transactions = client.transactions.list(account_id=account_id, limit=500)
# Convert to serializable format
export_data = []
for txn in transactions:
txn_data = txn.model_dump()
export_data.append(txn_data)
with open(filename, 'w', encoding='utf-8') as jsonfile:
json.dump(export_data, jsonfile, indent=2, default=str)
print(f"Exported {len(transactions)} transactions to {filename}")
# Usage
accounts = client.accounts.list()
export_transactions_csv(accounts[0].id)
export_transactions_json(accounts[0].id)