github.com/MicahParks/go-rsi@v1.0.7/float64.go (about) 1 package rsi 2 3 // DefaultPeriods is the default number of periods for the averages for the RSI algorithm. 4 const DefaultPeriods = 14 5 6 // Input represents the averages for a period that are inputted into the RSI algorithm. 7 type Input struct { 8 AverageGain float64 9 AverageLoss float64 10 } 11 12 // RSI represents the state of a Relative Strength Index (RSI) algorithm. 13 type RSI struct { 14 periods float64 15 periodsMinusOne float64 16 previous Input 17 } 18 19 // New creates a new RSI data structure and returns the initial result. 20 func New(periods uint, initial Input) (r *RSI, result float64) { 21 if periods == 0 { 22 periods = DefaultPeriods 23 } 24 25 r = &RSI{ 26 periods: float64(periods), 27 periodsMinusOne: float64(periods - 1), 28 previous: initial, 29 } 30 31 result = 100 - (100 / (1 + ((r.previous.AverageGain / r.periods) / (r.previous.AverageLoss / r.periods)))) 32 33 return r, result 34 } 35 36 // Calculate produces the next RSI result given the next input. 37 func (r *RSI) Calculate(next Input) (result float64) { 38 r.previous.AverageGain = (r.previous.AverageGain*(r.periodsMinusOne) + next.AverageGain) / r.periods 39 r.previous.AverageLoss = (r.previous.AverageLoss*(r.periodsMinusOne) + next.AverageLoss) / r.periods 40 41 result = 100 - 100/(1+r.previous.AverageGain/r.previous.AverageLoss) 42 43 return result 44 }