#! /bin/bash
# Last edited on 2015-02-23 22:00:40 by stolfilocal

# Arguments: {BESTSALE} {TITLE} {TSTEP} {REFDATE} {REFTIME} {MDPRICE} {LOPRICE} {HIPRICE} {DNAME}

# Reads the trade summary data file "00-DATA/series/fix/{DNAME}.txt"
# assumed to contain data for consecutive time intervals with {TSTEP} length and spacing,
# (in years) without missing intervals.
# 
# If {BESTSALE} is 0, plots the average yearly price gain
# factor from each date-time to some reference date-time ("{REFDATE}
# {REFTIME}") to every other time present in the file. Actually makes
# three plots, assuming that the final price is {MDPRICE}, {LOPRICE},
# and {HIPRICE}, respectively.
#
# If {BESTSALE} is 1, the yearly average gain factor is computed assuming the best possible sale
# after the buying date.  In that case only one plot is generated, and {MDPRICE}, {LOPRICE},
# and {HIPRICE} are ignored.
# 
# The plot data and image are saved as "predict/{DNAME}_apc_{IREF}.txt" for {IREF} = 0, 1, 2; and
# "predict/{DNAME}_apc.png".

bestsale="$1"; shift
title="$1"; shift
tstep="$1"; shift
refdate="$1"; shift
reftime="$1"; shift
mdprice="$1"; shift
loprice="$1"; shift
hiprice="$1"; shift
dname="$1"; shift

# Convert {tstep} from formula to numeric:
tstep=`echo "${tstep}" | bc -lq`
echo "tstep = ${tstep}" 1>&2

tmp="/tmp/$$"

inDir="../00-DATA/series/fix"

refprices=( ${mdprice} ${loprice} ${hiprice} )

if [[ ${bestsale} -ne 0 ]]; then 
  refindices=( 0 )
  opref="../predict/${dname}_abs"
else
  refindices=( 0 1 2 )
  opref="../predict/${dname}_apc"
fi

for iref in ${refindices[@]} ; do 
  refpr="${refprices[${iref}]}"
  echo "computing appreciation rates for final price ${refpr}" 1>&2
  cat ${inDir}/${dname}.txt \
    | egrep -v -e '(^[ ]*([#]|$))|[!]' \
    | compute_past_price_change_rates.gawk \
        -v tstep="${tstep}" \
        -v bestsale="${bestsale}" \
        -v refdate="${refdate}" \
        -v reftime="${reftime}" \
        -v refprice="${refpr}" \
    > ${opref}_${iref}.txt
done

# cat ${opref}.txt 1>&2

plot_price_change_rates.sh \
    SHOW ${bestsale} "${title}" "${refprices[@]}" \
    ${opref}

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