Search code examples
algorithmclojurestochastic

Explain how this stochastik function works


In the book "Clojure for Finance" I found a function like that:

(defn stochastic-k [last-price low-price high-price]
  (let [hlrange (- high-price low-price)
        hlmidpoint (/ hlrange 2)
        numerator (if (> last-price hlmidpoint)
                    (- last-price hlmidpoint)
                    (- hlmidpoint low-price))]
     (/ numerator hlrange)))

The author describes it as:

stochastic-k: This gives us our percentage of price movement of the high/low price.

(Quote and code from "Clojure for Finance", by Timothy Washington)

I tried the function in the REPL, but it's output doesn't make sense to me:

user=> (println (stochastic-k 18 13 23))
13/10

So the result is 1.3, but I would actually expect 1.0, because 18 is the midpoint of the range from 13 to 23, as far as I can tell.

Can anyone explain to me how the function is supposed to work?


Solution

  • There appears to be a bug in the implementation in my opinion. I think the numerator should be like:

    numerator (if (> last-price hlmidpoint)
                        (- last-price hlmidpoint)
                        (- hlmidpoint last-price))
    

    And then the function would produce a fraction representing how much does the last-price differ from the average price in the range.