~mikini/hometools

ref: 637040b13e70a39c89ba1e76df7dfeed6a0fe916 hometools/exchange_rates.sh -rwxr-xr-x 1.4 KiB
637040b1 — Mikkel Kirkgaard Nielsen Add COPYING and README.md 6 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#! /bin/bash
# Fetch daily ECB exchange rates and convert an amount from a base currency to a target currency

AMOUNTB=${1:-1}
AMOUNTB=$(echo ${AMOUNTB} | tr , .)
BASE=${2:-USD}
BASE=${BASE^^}
TARGET=${3:-DKK}
TARGET=${TARGET^^}
#VERBOSE=true

# ECB rates available from https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/index.en.html
# As XML http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
RATES=$(wget -q -O- http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml)
RATES=$(echo "$RATES"; echo "<Cube currency='EUR' rate='1'") # fake a EUR entry
BASEVAL=$(echo "$RATES" |egrep "<Cube currency='$BASE'" |egrep "rate='([[:digit:].]*)'" -o |egrep "[[:digit:].]*" -o)
TARGETVAL=$(echo "$RATES" |egrep "<Cube currency='$TARGET'" |egrep "rate='([[:digit:].]*)'" -o |egrep "[[:digit:].]*" -o)

if [ -z $BASEVAL ]; then
  echo "Base currency is not listed by ECB: $BASE." 
  exit
elif [ -z $TARGETVAL ]; then
  echo "Target currency is not listed by ECB: $TARGET."
  exit
fi

UNITYVAL=$(echo scale=5\;$TARGETVAL/$BASEVAL|bc)
AMOUNTT=$(echo scale=2\;$AMOUNTB*$TARGETVAL/$BASEVAL|bc)

if [ ! -z $VERBOSE ]; then
  echo "Base: $BASE, Target: $TARGET, Amount: $AMOUNTB."
  echo "Base  : EUR 1 = $BASE $BASEVAL"
  echo "Target: EUR 1 = $TARGET $TARGETVAL"
  echo "$BASE 1 = $TARGET $UNITYVAL"
fi
echo $BASE $AMOUNTB = $TARGET $AMOUNTT @ $UNITYVAL $TARGET/$BASE