# How To Compute Average True Range (ATR) using Haskell?

, in category: Third Party Scripts , 4 months ago

How To Compute Average True Range (ATR) using Haskell?

Member

by orpha , 4 months ago

To compute the Average True Range (ATR) using Haskell, you can follow these steps:

1. Define a function to calculate the true range:
 ```1 2 ``` ```trueRange :: Num a => [a] -> [a] trueRange xs = zipWith (a b -> maximum [abs (b-a), abs (b-(head xs)), abs (a-(head xs))]) xs (tail xs) ```

1. Define a function to calculate the average true range based on the true range values and the period (usually 14):
 ```1 2 3 4 5 ``` ```averageTrueRange :: (Fractional a, Ord a) => [a] -> Int -> a averageTrueRange prices period = sma (trueRange prices) period where sma :: (Fractional a) => [a] -> Int -> a sma xs n = sum (take n xs) / fromIntegral n ```

1. Now you can use this function with a list of price values and the desired period to calculate the ATR:
 ```1 2 3 4 ``` ```let prices = [10, 12, 15, 13, 17, 14, 16, 19, 18, 20, 23, 21, 24, 22] let period = 14 let atr = averageTrueRange prices period print atr ```

This will calculate the Average True Range (ATR) for the given price values and period.