#! /bin/bash
# Last edited on 2014-05-10 20:55:54 by stolfilocal

# Plots histograms of prediction errors.
# 
# Arguments: {EX} {BWID} {IDATE} {FDATE} 
# 
# Where 
#   
#   {EX} is the exchange code ("HUBI", "BSTP", etc.); 
#   {BWID} is the histogram bin width (an odd integer); 
#   {IDATE,FDATE} range of dates to consider.
#   
# Reads the file "2014-slumber-predictions-{EX}.txt, expected to contain
# the slumber confidence weights, and actual and predicted prices of
# exchage {EX}, at slumber times. Compares each prediction to the actual
# values for entries with the date inthe range {IDATE..FDATE}.
# Prints statistics of the prediction errors. Saves a weighted
# histogram of the errors to file
# "2014-slumber-predictions-{EX}-hist.txt" and a plot of the same to
# "2014-slumber-predictions-{EX}-hist.png".
#
# Assumes that the prices are integers.

ex="$1"; shift     # Exchange tag.
bwid="$1"; shift   # Histogram bin width.
idate="$1"; shift  # Initial date to consider.
fdate="$1"; shift  # Final date to consider.

title="Prediction errors for ${ex} in ${idate} -- ${fdate}"

show="SHOW"

tmp="/tmp/$$"

# Files
pfile="2014-slumber-predictions-${ex}.txt"      # Input file with prediction data.
hfile="${idate}--${fdate}-slumber-predictions-${ex}-hist.txt" # Histogram data file.
hplot="${idate}--${fdate}-slumber-predictions-${ex}-hist.png"  # Histogram plot image.
jplot="${idate}--${fdate}-slumber-predictions-${ex}-hist.jpg"  # Reduced size plot image for posting.

# Evaluate and generate histogram:
./compute_predictions_hist.gawk \
    -v bwid=${bwid} \
    -v idate=${idate} \
    -v fdate=${fdate} \
    ${pfile} \
  > ${hfile}

# cat ${hfile} 1>&2;

color=( '#0022ff' '#ff0000' '#008800' '#8800dd' '#dd4400' '#0066ff' )

export GDFONTPATH=.:..

gnuplot <<EOF
set term png size 2400,800 font "courbd,24"
set output "${tmp}-full.png"
set title "${title}"

bwid = ${bwid}
esh = 0.15*bwid # Displacement of histograms.
xmid(i,j,k,n) = 0.5*(column(i) + column(j)) + esh*(k - 0.5*(n - 1))

set yrange [-0.01:]
set grid ytics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'
set grid mytics

set grid xtics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'
set grid mxtics
set key top left

plot \
  "${hfile}" using (xmid(1,2,0,2)):3 title "Slumber" with histeps lt 1 lw 1.0 lc rgb '${color[0]}', \
  ""         using (xmid(1,2,1,2)):4 title "Banal"   with histeps lt 1 lw 1.0 lc rgb '${color[1]}'
    
quit
EOF

convert ${tmp}-full.png -resize '50%' ${hplot}
convert ${hplot} -resize '600x' ${jplot}

if [[ "/${show}" == "/SHOW" ]]; then
  if [[ -s ${hplot} ]]; then
    display ${hplot}
  fi
fi

rm -fv ${tmp}{-*,}.*
    
        
