|
| 1 | +{-# OPTIONS_HADDOCK show-extensions #-} |
| 2 | + |
| 3 | +module Bfx.Indicator.Rsi |
| 4 | + ( Rsi (..), |
| 5 | + RsiPeriod (..), |
| 6 | + defRsiPeriod, |
| 7 | + mkRsiConduit, |
| 8 | + ) |
| 9 | +where |
| 10 | + |
| 11 | +import Bfx.Data.Type |
| 12 | +import Conduit ((.|)) |
| 13 | +import qualified Conduit as C |
| 14 | +import qualified Data.Conduit.List as C |
| 15 | +import Functora.Money |
| 16 | +import Functora.Prelude |
| 17 | + |
| 18 | +newtype Rsi = Rsi |
| 19 | + { unRsi :: Ratio Natural |
| 20 | + } |
| 21 | + deriving stock |
| 22 | + ( Eq, |
| 23 | + Ord, |
| 24 | + Show, |
| 25 | + Read, |
| 26 | + Data, |
| 27 | + Generic |
| 28 | + ) |
| 29 | + |
| 30 | +newtype RsiPeriod = RsiPeriod |
| 31 | + { unRsiPeriod :: Natural |
| 32 | + } |
| 33 | + deriving stock |
| 34 | + ( Eq, |
| 35 | + Ord, |
| 36 | + Show, |
| 37 | + Read, |
| 38 | + Data, |
| 39 | + Generic |
| 40 | + ) |
| 41 | + |
| 42 | +defRsiPeriod :: RsiPeriod |
| 43 | +defRsiPeriod = RsiPeriod 14 |
| 44 | + |
| 45 | +mkRsiConduit :: |
| 46 | + ( Monad m |
| 47 | + ) => |
| 48 | + (a -> Candle) -> |
| 49 | + RsiPeriod -> |
| 50 | + C.ConduitT a (a, Rsi) m () |
| 51 | +mkRsiConduit mkCandle (RsiPeriod natPer) = |
| 52 | + C.slidingWindowC 2 |
| 53 | + .| ( whileM $ do |
| 54 | + mcandles <- fmap (>>= nonEmpty) C.await |
| 55 | + case mcandles of |
| 56 | + Just [c1, c2] -> do |
| 57 | + let p1 = mkCandle c1 ^. #candleClose . #unQuotePerBase |
| 58 | + let p2 = mkCandle c2 ^. #candleClose . #unQuotePerBase |
| 59 | + C.yield |
| 60 | + ( c2, |
| 61 | + -- Loss |
| 62 | + if p1 >= p2 |
| 63 | + then p1 - p2 |
| 64 | + else 0, |
| 65 | + -- Gain |
| 66 | + if p1 <= p2 |
| 67 | + then p2 - p1 |
| 68 | + else 0 |
| 69 | + ) |
| 70 | + pure True |
| 71 | + _ -> |
| 72 | + pure False |
| 73 | + ) |
| 74 | + .| ( do |
| 75 | + seed <- C.take intPer |
| 76 | + when (length seed == intPer) $ do |
| 77 | + let initAvgLoss = sum (fmap snd3 seed) / ratPer |
| 78 | + let initAvgGain = sum (fmap thd3 seed) / ratPer |
| 79 | + flip loopM (initAvgLoss, initAvgGain) |
| 80 | + $ \(prevAvgLoss, prevAvgGain) -> do |
| 81 | + mcandle <- C.await |
| 82 | + case mcandle of |
| 83 | + Nothing -> pure $ Right () |
| 84 | + Just (c, loss, gain) -> do |
| 85 | + let nextAvgLoss = prevAvgLoss * (ratPer - 1) + loss / ratPer |
| 86 | + let nextAvgGain = prevAvgGain * (ratPer - 1) + gain / ratPer |
| 87 | + let rs = nextAvgGain / nextAvgLoss |
| 88 | + let rsi = Rsi $ 100 - (100 / (1 + rs)) |
| 89 | + C.yield (c, rsi) |
| 90 | + pure $ Left (nextAvgLoss, nextAvgGain) |
| 91 | + ) |
| 92 | + where |
| 93 | + ratPer = from @Natural @(Ratio Natural) natPer |
| 94 | + intPer = |
| 95 | + case unsafeFrom @Natural @Int natPer of |
| 96 | + x | x < 2 -> error $ "Bad RSI period " <> inspect natPer |
| 97 | + x -> x |
0 commit comments