diff --git a/src/indicator/volume/onBalanceVolume.test.ts b/src/indicator/volume/onBalanceVolume.test.ts new file mode 100644 index 0000000..0351bc8 --- /dev/null +++ b/src/indicator/volume/onBalanceVolume.test.ts @@ -0,0 +1,16 @@ +// Copyright (c) 2022 Onur Cinar. All Rights Reserved. +// https://github.com/cinar/indicatorts + +import { roundDigitsAll } from '../../index'; +import { onBalanceVolume } from './onBalanceVolume'; + +describe('On Balance Volume (OBV)', () => { + it('should be able to compute OBV', () => { + const closings = [9, 11, 7, 10, 8]; + const volumes = [100, 110, 80, 120, 90]; + const expected = [0, 110, 30, 150, 60]; + + const actual = onBalanceVolume(closings, volumes); + expect(roundDigitsAll(2, actual)).toStrictEqual(expected); + }); +}); diff --git a/src/indicator/volume/onBalanceVolume.ts b/src/indicator/volume/onBalanceVolume.ts index fa18a5e..684ac72 100644 --- a/src/indicator/volume/onBalanceVolume.ts +++ b/src/indicator/volume/onBalanceVolume.ts @@ -23,17 +23,15 @@ export function onBalanceVolume( const result = new Array(closings.length); + result[0] = 0; + for (let i = 1; i < result.length; i++) { - if (i === 0) { - result[i] = 0; - } else { - result[i] = result[i - 1]; + result[i] = result[i - 1]; - if (closings[i] > closings[i - 1]) { - result[i] += volumes[i]; - } else if (closings[i] < closings[i - 1]) { - result[i] -= volumes[i]; - } + if (closings[i] > closings[i - 1]) { + result[i] += volumes[i]; + } else if (closings[i] < closings[i - 1]) { + result[i] -= volumes[i]; } }