Skip to content

Commit 6ed68cd

Browse files
committed
faster RSI
1 parent 07fd86d commit 6ed68cd

File tree

1 file changed

+14
-12
lines changed
  • pub/bfx/src/Bfx/Indicator

1 file changed

+14
-12
lines changed

pub/bfx/src/Bfx/Indicator/Rsi.hs

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import Functora.Money
1616
import Functora.Prelude
1717

1818
newtype Rsi = Rsi
19-
{ unRsi :: Ratio Natural
19+
{ unRsi :: Double
2020
}
2121
deriving stock
2222
( Eq,
@@ -59,13 +59,15 @@ mkRsiConduit mkCandle (RsiPeriod natPer) =
5959
C.yield
6060
( c2,
6161
-- Loss
62-
if p1 >= p2
63-
then p1 - p2
64-
else 0,
62+
via @Rational @(Ratio Natural) @Double
63+
$ if p1 >= p2
64+
then p1 - p2
65+
else 0,
6566
-- Gain
66-
if p1 <= p2
67-
then p2 - p1
68-
else 0
67+
via @Rational @(Ratio Natural) @Double
68+
$ if p1 <= p2
69+
then p2 - p1
70+
else 0
6971
)
7072
pure True
7173
_ ->
@@ -74,23 +76,23 @@ mkRsiConduit mkCandle (RsiPeriod natPer) =
7476
.| ( do
7577
seed <- C.take intPer
7678
when (length seed == intPer) $ do
77-
let initAvgLoss = sum (fmap snd3 seed) / ratPer
78-
let initAvgGain = sum (fmap thd3 seed) / ratPer
79+
let initAvgLoss = sum (fmap snd3 seed) / dblPer
80+
let initAvgGain = sum (fmap thd3 seed) / dblPer
7981
flip loopM (initAvgLoss, initAvgGain)
8082
$ \(prevAvgLoss, prevAvgGain) -> do
8183
mcandle <- C.await
8284
case mcandle of
8385
Nothing -> pure $ Right ()
8486
Just (c, loss, gain) -> do
85-
let nextAvgLoss = (prevAvgLoss * (ratPer - 1) + loss) / ratPer
86-
let nextAvgGain = (prevAvgGain * (ratPer - 1) + gain) / ratPer
87+
let nextAvgLoss = (prevAvgLoss * (dblPer - 1) + loss) / dblPer
88+
let nextAvgGain = (prevAvgGain * (dblPer - 1) + gain) / dblPer
8789
let rs = nextAvgGain / nextAvgLoss
8890
let rsi = Rsi $ 100 - (100 / (1 + rs))
8991
C.yield (c, rsi)
9092
pure $ Left (nextAvgLoss, nextAvgGain)
9193
)
9294
where
93-
ratPer = from @Natural @(Ratio Natural) natPer
95+
dblPer = unsafeFrom @Natural @Double natPer
9496
intPer =
9597
case unsafeFrom @Natural @Int natPer of
9698
x | x < 2 -> error $ "Bad RSI period " <> inspect natPer

0 commit comments

Comments
 (0)