~mikini/hometools

ref: 158a6504d2be767f8ecff7fb28a79aed78c37d9b hometools/exchange_rates.sh -rwxr-xr-x 1.9 KiB
158a6504 — Mikkel Kirkgaard Nielsen Exit on network error & indicate date of rate used 3 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#! /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_RES=$?
if [ ! $RATES_RES -eq 0 ]; then
    echo -n "Failed retrieving ECB eurofxref: "
    case $RATES_RES in
	1) ERR=Generic ;;
	3) ERR=File ;;
	4) ERR=Network ;;
	5) ERR=SSL/TSL ;;
	8) ERR=Server\ response ;;
    esac
    echo "$ERR error!"
    exit 42
fi

# Parse rates for data needed
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)
DATE=$(echo "$RATES" |egrep "<Cube time=" |egrep "time='([[:digit:]-]{10})'" -o |egrep "[[:digit:]-]{10}" -o)
#CURRENCIES=$(echo "$RATES" |egrep "<Cube currency='([[:alpha:]])'" |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 \($DATE\)