Skip to content

Commit

Permalink
better normalization support
Browse files Browse the repository at this point in the history
  • Loading branch information
jbaron committed Dec 25, 2023
1 parent 2a0ca9b commit 4f513ef
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
11 changes: 9 additions & 2 deletions roboquant/src/main/kotlin/org/roboquant/common/TimeSeries.kt
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,9 @@ class TimeSeries(val timeline: Timeline, val values: DoubleArray) : Iterable<Obs
fun returns(n:Int = 1) = TimeSeries(timeline.drop(n), values.returns(n))

/**
* Normalize the values by dividing all values by the first value
* Normalize the values by dividing all the values by the first value that is finite
*/
fun normalize() = TimeSeries(timeline, values / values.first())
fun normalize(start: Double = 1.0) = TimeSeries(timeline, values.normalize(start))

/**
* Return the observation that contains the maximum value.
Expand Down Expand Up @@ -274,6 +274,13 @@ fun Map<String, TimeSeries>.flatten(noOverlap: Boolean = true): TimeSeries {
return TimeSeries(result)
}

/**
* Normalize all the timeseries in his map
*/
fun Map<String, TimeSeries>.normalize(start: Double = 1.0): Map<String, TimeSeries> {
return mapValues { it.value.normalize(start) }
}

/**
* Convert a sorted by time collection to a [TimeSeries] object
*/
Expand Down
8 changes: 8 additions & 0 deletions roboquant/src/main/kotlin/org/roboquant/common/extensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,14 @@ fun DoubleArray.diff(n: Int = 1): DoubleArray {
return result
}

/**
* Returns a normalized array
*/
fun DoubleArray.normalize(start: Double = 1.0): DoubleArray {
val first = (firstOrNull { it.isFinite() } ?: 1.0) / start
return this / first
}

/**
* Returns the index of the first maximum value
*/
Expand Down

0 comments on commit 4f513ef

Please sign in to comment.