beancount-price-fetch.pl 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/env perl
  2. use strict;
  3. use warnings;
  4. use POSIX qw/strftime/;
  5. use Finance::Quote;
  6. my $queryRunner = Finance::Quote->new();
  7. my $time = strftime("%F", localtime());
  8. my @currencies;
  9. my @stocks;
  10. open(my $LINES, "$ENV{HOME}/.ledger/commodities.txt") || die "Cannot open definition file: $!.\n";
  11. while (my $line = <$LINES>) {
  12. chomp($line);
  13. (my $type, my $name, my @rest) = split / /, $line;
  14. if ($type eq 's') {
  15. push @stocks, $name;
  16. } elsif ($type eq 'c') {
  17. push @currencies, $name;
  18. } else {
  19. next;
  20. }
  21. }
  22. close($LINES);
  23. open(my $output, ">>$ENV{HOME}/.ledger/prices.beancount") || die "Cannot open price data file: $!.\n";
  24. print "\n* $time\n\n";
  25. print $output "\n* $time\n\n";
  26. foreach my $stock (@stocks) {
  27. my %data = $queryRunner->fetch('nyse',$stock);
  28. printf "$time price $stock %.2f USD\n", $data{$stock, "price"};
  29. printf $output "$time price $stock %.2f USD\n", $data{$stock, "price"};
  30. }
  31. foreach my $currency (@currencies) {
  32. my $exchangeRate = $queryRunner->currency($currency ,"USD");
  33. printf "$time price $currency %.2f USD\n", $exchangeRate;
  34. printf $output "$time price $currency %.2f USD\n", $exchangeRate;
  35. }
  36. close($output);