#! /bin/bash
# Last edited on 2015-02-23 21:53:48 by stolfilocal

# Arguments: {RMAX} {DZMAX} {CONFPCT} {TITLE} {DNAME}

# Reads the exchange data file "../00-DATA/series/fix/{DNAME}.txt", extracts the 
# weighted mean prices, converts to a series of log10 mean prices {Z[i]}. Then 
# for several step sizes {r} up to {RMAX} computes and plots statstics 
# and histograms on the differences {Z[i+r]-Z[i]} as a function of {R}.  Also 
# fits some simple models to that data.
#
# This process is repeated thrice, using (respectively) time, accumulated BTC-volume, and 
# acumlated currency volume as the independent variable.  In all cases the independent
# variable is divided into consecutive equal intervals, and the BTC-volume and currency-volume 
# in each input (time) interval are interpolated if needed to produce the amounts in
# the new variable's interval.
#
# The histograms assume that the absolute differences {|Z[i+r]-Z[i]|} generally do not
# exceed {DZMAX}.  The plotted confidence interval lines will contain {CONFPCT} times the 
# total weight for each stride {r}.
# 
# The plot data and image are saved as "out/{DNAME}_var.txt",
# "out/{DNAME}_var.png".

rmax="$1"; shift
dzmax="$1"; shift
confpct="$1"; shift
title="$1"; shift
dname="$1"; shift

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

tmp="/tmp/$$"

dpref="${tmp}"

uvars=( "time" "vbtc" "vnat" )
usteps=( 1  2000   2000000 )

for ivar in 0 1 2 ; do
  uvar="${uvars[${ivar}]}"
  ustep=${usteps[${ivar}]}
  
  opref="out/${dname}_${uvar}_var"

  echo "=== extracting the ${uvar}-based series ===" 1>&2
  cat ${inDir}/${dname}.txt \
    | extract_time_or_volume_series.gawk \
        -v which="${uvar}" \
        -v ustep="${ustep}" \
    > ${tmp}_${uvar}.dat
    
  # echo "=== ${tmp}_${uvar}.dat ==="
  # head ${tmp}_${uvar}.dat

  echo "=== computing the stride data and fitting the model ===" 1>&2
  cat ${tmp}_${uvar}.dat \
    | compute_future_uncertainty.gawk \
        -f ../find_percentile.gawk \
        -v opref="${dpref}" \
        -v rmax="${rmax}" \
        -v confpct="${confpct}"

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

  echo "=== ${dpref}_i.txt ==="
  head ${dpref}_i.txt
  
  echo "=== ${dpref}_r.txt ==="
  head ${dpref}_r.txt
  
  echo "=== building the deviation histogram ===" 1>&2
  cat ${dpref}_i.txt \
    | build_increment_time_histogram_image.gawk \
        -f ../write_fni_image.gawk \
        -v rmax="${rmax}" \
        -v nh=20 \
        -v dzmax="${dzmax}" \
    > ${dpref}_h.fni

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

  echo "=== ${dpref}_h.txt ==="
  head ${dpref}_h.txt
  
  echo "=== showing the deviation histogram ===" 1>&2
  fni_view \
      -hist 1 \
      -scale 100 \
    < ${dpref}_h.fni

  echo "=== plotting the increments by {r} ===" 1>&2
  plot_future_uncertainty.sh SHOW "${uvar}" "${confpct}" "${title}" "${dpref}" "${opref}"

done

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