Gnucash import script
I decided to track my finances with Gnucash. My bank allows downloading statements in qif format which can be imported by Gnucash.
But here is the problem: during the import the only way to classify your transactions (was it car maintenance, rent, or dinning?) is to manually assign every imported transaction to the appropriate account. If I'm trying to analyze my last year expenses, then it becomes virtually impossible to do it manually.
So I came up with a simple ruby script:
#!/usr/bin/ruby
$patterns = [
[/^PSHELL OIL/, 'Expenses:Auto:Gas'],
[/^PCHEVRON/, 'Expenses:Auto:Gas'],
[/^PTHE BOXING CLUB/, 'Expenses:Entertainment:Recreation'],
[/^PEDWARDS MIRA MESA STDM/, 'Expenses:Entertainment:Music/Movies'],
[/^PULTRASTAR CINEMAS/, 'Expenses:Entertainment:Music/Movies'],
[/^PHOBBYTOWN USA/, 'Expenses:Hobbies'],
]
def setCategory(tx)
tx.each do |line|
$patterns.each do |pattern|
rx = pattern[0]
if rx.match(line)
l = pattern[1]
tx << "L#{l}"
return
end
end #patterns
end #line
end
out = File.new('out.qif', 'w')
tx = []
txCount = 0
missed = 0;
while gets
if /^\^/.match($_)
txCount = txCount+1
len = tx.length
setCategory(tx)
if(len == tx.length)
puts tx
puts "-------------------"
missed = missed +1
end
out.puts tx
out.puts '^'
tx = []
else
tx << $_
end
end
puts "Transactions: #{txCount} Missed: #{missed}"
This scripts reads stdin, and modifies transactions by adding description to it, according to set of regular expressions. I gave a subset of regular expressions, you will have to modify them to match your codes and your Gnucash account names.
The trick is to add "L" code line to each transaction description. The qif file format can be found here. We need to add "L" line which would match to a desirable account name in your Gnucash setup.
In order to make the task easier, the script outputs unrecognized transactions to stdout. You can look at it, and add appropriate filters until count of unrecognized transactions become minor.