From 1d447cf775dd8c4a613018fd55cb03d094905442 Mon Sep 17 00:00:00 2001 From: Patrick Cason Date: Mon, 15 Apr 2024 09:06:54 -0500 Subject: [PATCH] Fixing Documentation (#451) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Describe Request Updated all the documentation and bumped to 2.1.0 based on a few remaining code changes that were needed. Now the work I set out to do originally is completely finished. You're good to merge @cinar ! 👍 --- README.md | 200 +++---- package-lock.json | 326 +---------- package.json | 10 +- src/backtest/{index.md => README.md} | 35 +- src/chart/{index.md => README.md} | 25 +- src/indicator/momentum/README.md | 203 +++++++ .../momentum/chaikinOscillator.test.ts | 8 +- src/indicator/momentum/chaikinOscillator.ts | 6 +- src/indicator/momentum/index.md | 233 -------- .../percentagePriceOscillator.test.ts | 4 +- .../momentum/percentagePriceOscillator.ts | 13 +- .../percentageVolumeOscillator.test.ts | 4 +- .../momentum/percentageVolumeOscillator.ts | 13 +- src/indicator/momentum/priceRateOfChange.ts | 4 + .../momentum/relativeStrengthIndex.ts | 3 + src/indicator/trend/README.md | 517 ++++++++++++++++++ .../trend/chandeForecastOscillator.ts | 24 +- src/indicator/trend/index.md | 429 --------------- src/indicator/trend/index.ts | 2 +- ...movingAverageConvergenceDivergence.test.ts | 8 +- .../movingAverageConvergenceDivergence.ts | 8 +- src/indicator/trend/parabolicSar.test.ts | 4 +- src/indicator/trend/parabolicSar.ts | 30 +- .../{kdj.test.ts => randomIndex.test.ts} | 4 +- .../trend/{kdj.ts => randomIndex.ts} | 3 + src/indicator/volatility/README.md | 242 ++++++++ src/indicator/volatility/accelerationBands.ts | 8 +- .../volatility/averageTrueRange.test.ts | 8 +- src/indicator/volatility/averageTrueRange.ts | 8 +- src/indicator/volatility/chandelierExit.ts | 2 +- src/indicator/volatility/index.md | 180 ------ src/indicator/volatility/keltnerChannel.ts | 9 +- .../volatility/projectionOscillator.test.ts | 8 +- .../volatility/projectionOscillator.ts | 15 +- src/indicator/volume/{index.md => README.md} | 118 ++-- src/strategy/{index.md => README.md} | 37 +- src/strategy/momentum/README.md | 87 +++ src/strategy/momentum/index.md | 69 --- .../momentum/stochasticOscillatorStrategy.ts | 7 +- src/strategy/trend/README.md | 157 ++++++ src/strategy/trend/index.md | 132 ----- src/strategy/trend/kdjStrategy.ts | 6 +- src/strategy/trend/macdStrategy.ts | 6 +- src/strategy/volatility/README.md | 64 +++ src/strategy/volatility/index.md | 47 -- .../projectionOscillatorStrategy.ts | 6 +- src/strategy/volume/README.md | 109 ++++ src/strategy/volume/index.md | 80 --- 48 files changed, 1756 insertions(+), 1765 deletions(-) rename src/backtest/{index.md => README.md} (82%) rename src/chart/{index.md => README.md} (82%) create mode 100644 src/indicator/momentum/README.md delete mode 100644 src/indicator/momentum/index.md create mode 100644 src/indicator/trend/README.md delete mode 100644 src/indicator/trend/index.md rename src/indicator/trend/{kdj.test.ts => randomIndex.test.ts} (95%) rename src/indicator/trend/{kdj.ts => randomIndex.ts} (97%) create mode 100644 src/indicator/volatility/README.md delete mode 100644 src/indicator/volatility/index.md rename src/indicator/volume/{index.md => README.md} (52%) rename src/strategy/{index.md => README.md} (81%) create mode 100644 src/strategy/momentum/README.md delete mode 100644 src/strategy/momentum/index.md create mode 100644 src/strategy/trend/README.md delete mode 100644 src/strategy/trend/index.md create mode 100644 src/strategy/volatility/README.md delete mode 100644 src/strategy/volatility/index.md create mode 100644 src/strategy/volume/README.md delete mode 100644 src/strategy/volume/index.md diff --git a/README.md b/README.md index a2a767a..d95c88f 100644 --- a/README.md +++ b/README.md @@ -16,142 +16,141 @@ The following list of indicators are currently supported by this package: ### Trend Indicators -- [Absolute Price Oscillator (APO)](src/indicator/trend/index.md#absolute-price-oscillator-apo) -- [Aroon Indicator](src/indicator/trend/index.md#aroon-indicator) -- [Balance of Power (BOP)](src/indicator/trend/index.md#balance-of-power-bop) -- [Chande Forecast Oscillator (CFO)](src/indicator/trend/index.md#chande-forecast-oscillator-cfo) -- [Community Channel Index (CMI)](src/indicator/trend/index.md#community-channel-index-cmi) -- [Double Exponential Moving Average (DEMA)](src/indicator/trend/index.md#double-exponential-moving-average-dema) -- [Exponential Moving Average (EMA)](src/indicator/trend/index.md#exponential-moving-average-ema) -- [Mass Index (MI)](src/indicator/trend/index.md#mass-index-mi) -- [Moving Average Convergence Divergence (MACD)](src/indicator/trend/index.md#moving-average-convergence-divergence-macd) -- [Moving Max](src/indicator/trend/index.md#moving-max) -- [Moving Min](src/indicator/trend/index.md#moving-min) -- [Moving Sum](src/indicator/trend/index.md#moving-sum) -- [Parabolic SAR](src/indicator/trend/index.md#parabolic-sar) -- [Qstick](src/indicator/trend/index.md#qstick) -- [Random Index (KDJ)](src/indicator/trend/index.md#random-index-kdj) -- [Rolling Moving Average (RMA)](src/indicator/trend/index.md#rolling-moving-average-rma) -- [Simple Moving Average (SMA)](src/indicator/trend/index.md#simple-moving-average-sma) -- [Since Change](src/indicator/trend/index.md#since-change) -- [Triple Exponential Moving Average (TEMA)](src/indicator/trend/index.md#triple-exponential-moving-average-tema) -- [Triangular Moving Average (TRIMA)](src/indicator/trend/index.md#triangular-moving-average-trima) -- [Triple Exponential Average (TRIX)](#triple-exponential-average-trix) -- [Typical Price](src/indicator/trend/index.md#typical-price) -- [Volume Weighted Moving Average (VWMA)](src/indicator/trend/index.md#volume-weighted-moving-average-vwma) -- [Vortex Indicator](src/indicator/trend/index.md#vortex-indicator) +- [Absolute Price Oscillator (APO)](src/indicator/trend/README.md#absolute-price-oscillator-apo) +- [Aroon Indicator](src/indicator/trend/README.md#aroon) +- [Balance of Power (BOP)](src/indicator/trend/README.md#balance-of-power-bop) +- [Chande Forecast Oscillator (CFO)](src/indicator/trend/README.md#chande-forecast-oscillator-cfo) +- [Community Channel Index (CCI)](src/indicator/trend/README.md#community-channel-index-cci) +- [Double Exponential Moving Average (DEMA)](src/indicator/trend/README.md#double-exponential-moving-average-dema) +- [Exponential Moving Average (EMA)](src/indicator/trend/README.md#exponential-moving-average-ema) +- [Mass Index (MI)](src/indicator/trend/README.md#mass-index-mi) +- [Moving Average Convergence Divergence (MACD)](src/indicator/trend/README.md#moving-average-convergence-divergence-macd) +- [Moving Max (MMAX)](src/indicator/trend/README.md#moving-max-mmax) +- [Moving Min (MMIN)](src/indicator/trend/README.md#moving-min-mmin) +- [Moving Sum (MSUM)](src/indicator/trend/README.md#moving-sum-msum) +- [Parabolic SAR (PSAR)](src/indicator/trend/README.md#parabolic-sar-psar) +- [Qstick](src/indicator/trend/README.md#qstick) +- [Random Index (KDJ)](src/indicator/trend/README.md#random-index-kdj) +- [Rolling Moving Average (RMA)](src/indicator/trend/README.md#rolling-moving-average-rma) +- [Simple Moving Average (SMA)](src/indicator/trend/README.md#simple-moving-average-sma) +- [Since Change](src/indicator/trend/README.md#since-change) +- [Triple Exponential Moving Average (TEMA)](src/indicator/trend/README.md#triple-exponential-moving-average-tema) +- [Triangular Moving Average (TRIMA)](src/indicator/trend/README.md#triangular-moving-average-trima) +- [Triple Exponential Average (TRIX)](src/indicator/trend/README.md#triple-exponential-average-trix) +- [Typical Price](src/indicator/trend/README.md#typical-price) +- [Volume Weighted Moving Average (VWMA)](src/indicator/trend/README.md#volume-weighted-moving-average-vwma) +- [Vortex Indicator](src/indicator/trend/README.md#vortex-indicator) ### Momentum Indicators -- [Awesome Oscillator](src/indicator/momentum/index.md#awesome-oscillator) -- [Chaikin Oscillator](src/indicator/momentum/index.md#chaikin-oscillator) -- [Custom RSI](src/indicator/momentum/index.md#custom-rsi) -- [Ichimoku Cloud](src/indicator/momentum/index.md#ichimoku-cloud) -- [Percentage Price Oscillator (PPO)](src/indicator/momentum/index.md#percentage-price-oscillator-ppo) -- [Percentage Volume Oscillator (PVO)](src/indicator/momentum/index.md#percentage-volume-oscillator-pvo) -- [Price Rate of Change (ROC)](src/indicator/momentum/index.md#price-rate-of-change-roc) -- [Relative Strength Index (RSI)](src/indicator/momentum/index.md#relative-strength-index-rsi) -- [RSI 2](src/indicator/momentum/index.md#rsi-2) -- [Stochastic Oscillator](src/indicator/momentum/index.md#stochastic-oscillator) -- [Williams R](src/indicator/momentum/index.md#williams-r) +- [Awesome Oscillator (AO)](src/indicator/momentum/README.md#awesome-oscillator-ao) +- [Chaikin Oscillator (CMO)](src/indicator/momentum/README.md#chaikin-oscillator-cmo) +- [Ichimoku Cloud](src/indicator/momentum/README.md#ichimoku-cloud) +- [Percentage Price Oscillator (PPO)](src/indicator/momentum/README.md#percentage-price-oscillator-ppo) +- [Percentage Volume Oscillator (PVO)](src/indicator/momentum/README.md#percentage-volume-oscillator-pvo) +- [Price Rate of Change (ROC)](src/indicator/momentum/README.md#price-rate-of-change-roc) +- [Relative Strength Index (RSI)](src/indicator/momentum/README.md#relative-strength-index-rsi) +- [Stochastic Oscillator (STOCH)](src/indicator/momentum/README.md#stochastic-oscillator-stoch) +- [Williams R (WILLR)](src/indicator/momentum/README.md#williams-r-willr) ### Volatility Indicators -- [Acceleration Bands](src/indicator/volatility/index.md#acceleration-bands) -- [Average True Range (ATR)](src/indicator/volatility/index.md#average-true-range-atr) -- [Bollinger Band Width](src/indicator/volatility/index.md#bollinger-band-width) -- [Bollinger Bands](src/indicator/volatility/index.md#bollinger-bands) -- [Chandelier Exit](src/indicator/volatility/index.md#chandelier-exit) -- [Donchian Channel (DC)](src/indicator/volatility/index.md#donchian-channel-dc) -- [Keltner Channel (KC)](src/indicator/volatility/index.md#keltner-channel-kc) -- [Moving Standard Deviation (Std)](src/indicator/volatility/index.md#moving-standard-deviation-std) -- [Projection Oscillator (PO)](src/indicator/volatility/index.md#projection-oscillator-po) -- [Ulcer Index (UI)](src/indicator/volatility/index.md#ulcer-index-ui) +- [Acceleration Bands (AB)](src/indicator/volatility/README.md#acceleration-bands-ab) +- [Average True Range (ATR)](src/indicator/volatility/README.md#average-true-range-atr) +- [Bollinger Bands (BB)](src/indicator/volatility/README.md#bollinger-bands-bb) +- [Bollinger Band Width (BBW)](src/indicator/volatility/README.md#bollinger-band-width-bbw) +- [Chandelier Exit (CE)](src/indicator/volatility/README.md#chandelier-exit-ce) +- [Donchian Channel (DC)](src/indicator/volatility/README.md#donchian-channel-dc) +- [Keltner Channel (KC)](src/indicator/volatility/README.md#keltner-channel-kc) +- [Moving Standard Deviation (MSTD)](src/indicator/volatility/README.md#moving-standard-deviation-mstd) +- [Projection Oscillator (PO)](src/indicator/volatility/README.md#projection-oscillator-po) +- [True Range (TR)](src/indicator/volatility/README.md#true-range-tr) +- [Ulcer Index (UI)](src/indicator/volatility/README.md#ulcer-index-ui) ### Volume Indicators -- [Accumulation/Distribution (A/D)](src/indicator/volume/index.md#accumulationdistribution-ad) -- [Chaikin Money Flow (CMF)](src/indicator/volume/index.md#chaikin-money-flow-cmf) -- [Ease of Movement (EMV)](src/indicator/volume/index.md#ease-of-movement-emv) -- [Force Index (FI)](src/indicator/volume/index.md#force-index-fi) -- [Money Flow Index (MFI)](src/indicator/volume/index.md#money-flow-index-mfi) -- [Negative Volume Index (NVI)](src/indicator/volume/index.md#negative-volume-index-nvi) -- [On-Balance Volume (OBV)](src/indicator/volume/index.md#on-balance-volume-obv) -- [Volume Price Trend (VPT)](src/indicator/volume/index.md#volume-price-trend-vpt) -- [Volume Weighted Average Price (VWAP)](src/indicator/volume/index.md#volume-weighted-average-price-vwap) +- [Accumulation/Distribution (AD)](src/indicator/volume/README.md#accumulationdistribution-ad) +- [Chaikin Money Flow (CMF)](src/indicator/volume/README.md#chaikin-money-flow-cmf) +- [Ease of Movement (EMV)](src/indicator/volume/README.md#ease-of-movement-emv) +- [Force Index (FI)](src/indicator/volume/README.md#force-index-fi) +- [Money Flow Index (MFI)](src/indicator/volume/README.md#money-flow-index-mfi) +- [Negative Volume Index (NVI)](src/indicator/volume/README.md#negative-volume-index-nvi) +- [On-Balance Volume (OBV)](src/indicator/volume/README.md#on-balance-volume-obv) +- [Volume Price Trend (VPT)](src/indicator/volume/README.md#volume-price-trend-vpt) +- [Volume Weighted Average Price (VWAP)](src/indicator/volume/README.md#volume-weighted-average-price-vwap) ## Strategies Provided Strategies relies on the following: -- [Asset](src/strategy/index.md#asset) - - [New Asset with Length](src/strategy/index.md#new-asset-with-length) - - [Concat Assets](src/strategy/index.md#concat-assets) -- [Action](src/strategy/index.md#action) - - [Reverse Actions](src/strategy/index.md#reverse-actions) - - [Apply Actions](src/strategy/index.md#apply-actions) -- [Strategy Function](src/strategy/index.md#strategy-function) -- [Buy and Hold Strategy](src/strategy/index.md#buy-and-hold-strategy) +- [Asset](src/strategy/README.md#asset) + - [New Asset with Length](src/strategy/README.md#new-asset-with-length) + - [Concat Assets](src/strategy/README.md#concat-assets) +- [Action](src/strategy/README.md#action) + - [Reverse Actions](src/strategy/README.md#reverse-actions) + - [Apply Actions](src/strategy/README.md#apply-actions) +- [Strategy Function](src/strategy/README.md#strategy-function) +- [Buy and Hold Strategy](src/strategy/README.md#buy-and-hold-strategy) The following list of strategies are currently supported by this package: ### Trend Strategies -- [Absolute Price Oscillator Strategy](src/strategy/trend/index.md#absolute-price-oscillator-strategy) -- [Aroon Strategy](src/strategy/trend/index.md#aroon-strategy) -- [Balance of Power Strategy](src/strategy/trend/index.md#balance-of-power-strategy) -- [Chande Forecast Oscillator Strategy](src/strategy/trend/index.md#chande-forecast-oscillator-strategy) -- [MACD Strategy](src/strategy/trend/index.md#macd-strategy) -- [KDJ Strategy](src/strategy/trend/index.md#kdj-strategy) -- [Parabolic SAR Strategy](src/strategy/trend/index.md#parabolic-sar-strategy) -- [Typical Price Strategy](src/strategy/trend/index.md#typical-price-strategy) -- [Volume Weighted Moving Average (VWMA) Strategy](src/strategy/trend/index.md#volume-weighted-moving-average-vwma-strategy) -- [Vortex Strategy](src/strategy/trend/index.md#vortex-strategy) +- [Absolute Price Oscillator Strategy](src/strategy/trend/README.md#absolute-price-oscillator-strategy) +- [Aroon Strategy](src/strategy/trend/README.md#aroon-strategy) +- [Balance of Power Strategy](src/strategy/trend/README.md#balance-of-power-strategy) +- [Chande Forecast Oscillator Strategy](src/strategy/trend/README.md#chande-forecast-oscillator-strategy) +- [KDJ Strategy](src/strategy/trend/README.md#kdj-strategy) +- [MACD Strategy](src/strategy/trend/README.md#macd-strategy) +- [Parabolic SAR Strategy](src/strategy/trend/README.md#parabolic-sar-strategy) +- [Typical Price Strategy](src/strategy/trend/README.md#typical-price-strategy) +- [Volume Weighted Moving Average (VWMA) Strategy](src/strategy/trend/README.md#volume-weighted-moving-average-vwma-strategy) +- [Vortex Strategy](src/strategy/trend/README.md#vortex-strategy) ### Momentum Strategies -- [Awesome Oscillator Strategy](src/strategy/momentum/index.md#awesome-oscillator-strategy) -- [Ichimoku Cloud Strategy](src/strategy/momentum/index.md#ichimoku-cloud-strategy) -- [RSI 2 Stategy](src/strategy/momentum/index.md#rsi-2-strategy) -- [Stochastic Oscillator Strategy](src/strategy/momentum/index.md#stochastic-oscillator-strategy) -- [Williams R Strategy](src/strategy/momentum/index.md#williams-r-strategy) +- [Awesome Oscillator Strategy](src/strategy/momentum/README.md#awesome-oscillator-strategy) +- [Ichimoku Cloud Strategy](src/strategy/momentum/README.md#ichimoku-cloud-strategy) +- [RSI 2 Stategy](src/strategy/momentum/README.md#rsi-2-strategy) +- [Stochastic Oscillator Strategy](src/strategy/momentum/README.md#stochastic-oscillator-strategy) +- [Williams R Strategy](src/strategy/momentum/README.md#williams-r-strategy) ### Volatility Strategies -- [Acceleration Bands Strategy](src/strategy/volatility/index.md#acceleration-bands-strategy) -- [Bollinger Bands Strategy](src/strategy/volatility/index.md#bollinger-bands-strategy) -- [Projection Oscillator Strategy](src/strategy/volatility/index.md#projection-oscillator-strategy) +- [Acceleration Bands Strategy](src/strategy/volatility/README.md#acceleration-bands-strategy) +- [Bollinger Bands Strategy](src/strategy/volatility/README.md#bollinger-bands-strategy) +- [Projection Oscillator Strategy](src/strategy/volatility/README.md#projection-oscillator-strategy) ### Volume Strategies -- [Chaikin Money Flow Strategy](src/strategy/volume/index.md#chaikin-money-flow-strategy) -- [Ease of Movement Strategy](src/strategy/volume/index.md#ease-of-movement-strategy) -- [Force Index Strategy](src/strategy/volume/index.md#force-index-strategy) -- [Money Flow Index Strategy](src/strategy/volume/index.md#money-flow-index-strategy) -- [Negative Volume Index Strategy](src/strategy/volume/index.md#negative-volume-index-strategy) -- [Volume Weighted Average Price Strategy](src/strategy/volume/index.md#volume-weighted-average-price-strategy) +- [Chaikin Money Flow Strategy](src/strategy/volume/README.md#chaikin-money-flow-strategy) +- [Ease of Movement Strategy](src/strategy/volume/README.md#ease-of-movement-strategy) +- [Force Index Strategy](src/strategy/volume/README.md#force-index-strategy) +- [Money Flow Index Strategy](src/strategy/volume/README.md#money-flow-index-strategy) +- [Negative Volume Index Strategy](src/strategy/volume/README.md#negative-volume-index-strategy) +- [Volume Weighted Average Price Strategy](src/strategy/volume/README.md#volume-weighted-average-price-strategy) ## Backtest Backtesting is the method for seeing how well a strategy would have done. The following backtesting functions are provided for evaluating strategies. -- [Strategy Info](src/backtest/index.md#strategy-info) -- [Strategy Result](src/backtest/index.md#strategy-result) -- [Backtest Function](src/backtest/index.md#backtest-function) -- [Company Info](src/backtest/index.md#company-info) -- [Company Result](src/backtest/index.md#company-result) -- [Strategy Stats](src/backtest/index.md#strategy-stats) - - [Compute Strategy Stats](src/backtest/index.md#compute-strategy-stats) +- [Strategy Info](src/backtest/README.md#strategy-info) +- [Strategy Result](src/backtest/README.md#strategy-result) +- [Backtest Function](src/backtest/README.md#backtest-function) +- [Company Info](src/backtest/README.md#company-info) +- [Company Result](src/backtest/README.md#company-result) +- [Strategy Stats](src/backtest/README.md#strategy-stats) + - [Compute Strategy Stats](src/backtest/README.md#compute-strategy-stats) ## Chart Chart provides an easy way to plot the outcome of the indicators and the strategies. -- [Chart Initialization](src/chart/index.md#chart-initialization) -- [Data Set](src/chart/index.md#data-set) -- [Add Data](src/chart/index.md#add-data) -- [Remove Data](src/chart/index.md#remove-data) -- [Draw Chart](src/chart/index.md#draw-chart) +- [Chart Initialization](src/chart/README.md#chart-initialization) +- [Data Set](src/chart/README.md#data-set) +- [Add Data](src/chart/README.md#add-data) +- [Remove Data](src/chart/README.md#remove-data) +- [Draw Chart](src/chart/README.md#draw-chart) ## Build @@ -172,12 +171,13 @@ npm install indicatorts Import indicator. ```TypeScript -import {awesomeOscillator} from 'indicatorts'; +import { ao } from 'indicatorts'; const highs = [10, 20, 30, 40]; const lows = [1, 2, 3, 4]; -const ao = awesomeOscillator(highs, lows); +// Awesome Oscillator! +const result = ao(highs, lows); ``` ## Disclaimer diff --git a/package-lock.json b/package-lock.json index 6e9d310..a80ed49 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,24 +1,24 @@ { "name": "indicatorts", - "version": "2.0.0", + "version": "2.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "indicatorts", - "version": "2.0.0", + "version": "2.1.0", "license": "MIT", "devDependencies": { "@types/jest": "^29.5.12", - "@typescript-eslint/eslint-plugin": "^7.1.0", - "@typescript-eslint/parser": "^7.1.0", - "esbuild": "^0.20.1", + "@typescript-eslint/eslint-plugin": "^7.6.0", + "@typescript-eslint/parser": "^7.6.0", + "esbuild": "^0.20.2", "eslint": "^8.57.0", "eslint-config-prettier": "^9.1.0", "jest": "^29.7.0", "prettier": "^3.2.5", "ts-jest": "^29.1.2", - "typescript": "^5.3.3" + "typescript": "^5.4.5" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -1847,53 +1847,6 @@ } } }, - "node_modules/@typescript-eslint/eslint-plugin/node_modules/@typescript-eslint/scope-manager": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.6.0.tgz", - "integrity": "sha512-ngttyfExA5PsHSx0rdFgnADMYQi+Zkeiv4/ZxGYUWd0nLs63Ha0ksmp8VMxAIC0wtCFxMos7Lt3PszJssG/E6w==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "7.6.0", - "@typescript-eslint/visitor-keys": "7.6.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/eslint-plugin/node_modules/@typescript-eslint/types": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.6.0.tgz", - "integrity": "sha512-h02rYQn8J+MureCvHVVzhl69/GAfQGPQZmOMjG1KfCl7o3HtMSlPaPUAPu6lLctXI5ySRGIYk94clD/AUMCUgQ==", - "dev": true, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/eslint-plugin/node_modules/@typescript-eslint/visitor-keys": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.6.0.tgz", - "integrity": "sha512-4eLB7t+LlNUmXzfOu1VAIAdkjbu5xNSerURS9X/S5TUKWFRpXRQZbmtPqgKmYx8bj3J0irtQXSiWAOY82v+cgw==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "7.6.0", - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, "node_modules/@typescript-eslint/parser": { "version": "7.6.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.6.0.tgz", @@ -1922,7 +1875,7 @@ } } }, - "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/scope-manager": { + "node_modules/@typescript-eslint/scope-manager": { "version": "7.6.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.6.0.tgz", "integrity": "sha512-ngttyfExA5PsHSx0rdFgnADMYQi+Zkeiv4/ZxGYUWd0nLs63Ha0ksmp8VMxAIC0wtCFxMos7Lt3PszJssG/E6w==", @@ -1939,96 +1892,6 @@ "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/types": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.6.0.tgz", - "integrity": "sha512-h02rYQn8J+MureCvHVVzhl69/GAfQGPQZmOMjG1KfCl7o3HtMSlPaPUAPu6lLctXI5ySRGIYk94clD/AUMCUgQ==", - "dev": true, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/typescript-estree": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.6.0.tgz", - "integrity": "sha512-+7Y/GP9VuYibecrCQWSKgl3GvUM5cILRttpWtnAu8GNL9j11e4tbuGZmZjJ8ejnKYyBRb2ddGQ3rEFCq3QjMJw==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "7.6.0", - "@typescript-eslint/visitor-keys": "7.6.0", - "debug": "^4.3.4", - "globby": "^11.1.0", - "is-glob": "^4.0.3", - "minimatch": "^9.0.4", - "semver": "^7.6.0", - "ts-api-utils": "^1.3.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/visitor-keys": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.6.0.tgz", - "integrity": "sha512-4eLB7t+LlNUmXzfOu1VAIAdkjbu5xNSerURS9X/S5TUKWFRpXRQZbmtPqgKmYx8bj3J0irtQXSiWAOY82v+cgw==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "7.6.0", - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/parser/node_modules/minimatch": { - "version": "9.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.4.tgz", - "integrity": "sha512-KqWh+VchfxcMNRAJjj2tnsSJdNbHsVgnkBhTNrW7AjVo6OvLtxw8zfT9oLw1JSohlFzJ8jCoTgaoXvJ+kHt6fw==", - "dev": true, - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.1.0.tgz", - "integrity": "sha512-6TmN4OJiohHfoOdGZ3huuLhpiUgOGTpgXNUPJgeZOZR3DnIpdSgtt83RS35OYNNXxM4TScVlpVKC9jyQSETR1A==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "7.1.0", - "@typescript-eslint/visitor-keys": "7.1.0" - }, - "engines": { - "node": "^16.0.0 || >=18.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, "node_modules/@typescript-eslint/type-utils": { "version": "7.6.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.6.0.tgz", @@ -2056,7 +1919,7 @@ } } }, - "node_modules/@typescript-eslint/type-utils/node_modules/@typescript-eslint/types": { + "node_modules/@typescript-eslint/types": { "version": "7.6.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.6.0.tgz", "integrity": "sha512-h02rYQn8J+MureCvHVVzhl69/GAfQGPQZmOMjG1KfCl7o3HtMSlPaPUAPu6lLctXI5ySRGIYk94clD/AUMCUgQ==", @@ -2069,7 +1932,7 @@ "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/@typescript-eslint/type-utils/node_modules/@typescript-eslint/typescript-estree": { + "node_modules/@typescript-eslint/typescript-estree": { "version": "7.6.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.6.0.tgz", "integrity": "sha512-+7Y/GP9VuYibecrCQWSKgl3GvUM5cILRttpWtnAu8GNL9j11e4tbuGZmZjJ8ejnKYyBRb2ddGQ3rEFCq3QjMJw==", @@ -2097,79 +1960,6 @@ } } }, - "node_modules/@typescript-eslint/type-utils/node_modules/@typescript-eslint/visitor-keys": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.6.0.tgz", - "integrity": "sha512-4eLB7t+LlNUmXzfOu1VAIAdkjbu5xNSerURS9X/S5TUKWFRpXRQZbmtPqgKmYx8bj3J0irtQXSiWAOY82v+cgw==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "7.6.0", - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/type-utils/node_modules/minimatch": { - "version": "9.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.4.tgz", - "integrity": "sha512-KqWh+VchfxcMNRAJjj2tnsSJdNbHsVgnkBhTNrW7AjVo6OvLtxw8zfT9oLw1JSohlFzJ8jCoTgaoXvJ+kHt6fw==", - "dev": true, - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@typescript-eslint/types": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.1.0.tgz", - "integrity": "sha512-qTWjWieJ1tRJkxgZYXx6WUYtWlBc48YRxgY2JN1aGeVpkhmnopq+SUC8UEVGNXIvWH7XyuTjwALfG6bFEgCkQA==", - "dev": true, - "engines": { - "node": "^16.0.0 || >=18.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.1.0.tgz", - "integrity": "sha512-k7MyrbD6E463CBbSpcOnwa8oXRdHzH1WiVzOipK3L5KSML92ZKgUBrTlehdi7PEIMT8k0bQixHUGXggPAlKnOQ==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "7.1.0", - "@typescript-eslint/visitor-keys": "7.1.0", - "debug": "^4.3.4", - "globby": "^11.1.0", - "is-glob": "^4.0.3", - "minimatch": "9.0.3", - "semver": "^7.5.4", - "ts-api-utils": "^1.0.1" - }, - "engines": { - "node": "^16.0.0 || >=18.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, "node_modules/@typescript-eslint/utils": { "version": "7.6.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.6.0.tgz", @@ -2195,65 +1985,7 @@ "eslint": "^8.56.0" } }, - "node_modules/@typescript-eslint/utils/node_modules/@typescript-eslint/scope-manager": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.6.0.tgz", - "integrity": "sha512-ngttyfExA5PsHSx0rdFgnADMYQi+Zkeiv4/ZxGYUWd0nLs63Ha0ksmp8VMxAIC0wtCFxMos7Lt3PszJssG/E6w==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "7.6.0", - "@typescript-eslint/visitor-keys": "7.6.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/utils/node_modules/@typescript-eslint/types": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.6.0.tgz", - "integrity": "sha512-h02rYQn8J+MureCvHVVzhl69/GAfQGPQZmOMjG1KfCl7o3HtMSlPaPUAPu6lLctXI5ySRGIYk94clD/AUMCUgQ==", - "dev": true, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/utils/node_modules/@typescript-eslint/typescript-estree": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.6.0.tgz", - "integrity": "sha512-+7Y/GP9VuYibecrCQWSKgl3GvUM5cILRttpWtnAu8GNL9j11e4tbuGZmZjJ8ejnKYyBRb2ddGQ3rEFCq3QjMJw==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "7.6.0", - "@typescript-eslint/visitor-keys": "7.6.0", - "debug": "^4.3.4", - "globby": "^11.1.0", - "is-glob": "^4.0.3", - "minimatch": "^9.0.4", - "semver": "^7.6.0", - "ts-api-utils": "^1.3.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/utils/node_modules/@typescript-eslint/visitor-keys": { + "node_modules/@typescript-eslint/visitor-keys": { "version": "7.6.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.6.0.tgz", "integrity": "sha512-4eLB7t+LlNUmXzfOu1VAIAdkjbu5xNSerURS9X/S5TUKWFRpXRQZbmtPqgKmYx8bj3J0irtQXSiWAOY82v+cgw==", @@ -2270,38 +2002,6 @@ "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/@typescript-eslint/utils/node_modules/minimatch": { - "version": "9.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.4.tgz", - "integrity": "sha512-KqWh+VchfxcMNRAJjj2tnsSJdNbHsVgnkBhTNrW7AjVo6OvLtxw8zfT9oLw1JSohlFzJ8jCoTgaoXvJ+kHt6fw==", - "dev": true, - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.1.0.tgz", - "integrity": "sha512-FhUqNWluiGNzlvnDZiXad4mZRhtghdoKW6e98GoEOYSu5cND+E39rG5KwJMUzeENwm1ztYBRqof8wMLP+wNPIA==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "7.1.0", - "eslint-visitor-keys": "^3.4.1" - }, - "engines": { - "node": "^16.0.0 || >=18.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, "node_modules/@ungap/structured-clone": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.0.tgz", @@ -4550,9 +4250,9 @@ } }, "node_modules/minimatch": { - "version": "9.0.3", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.3.tgz", - "integrity": "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==", + "version": "9.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.4.tgz", + "integrity": "sha512-KqWh+VchfxcMNRAJjj2tnsSJdNbHsVgnkBhTNrW7AjVo6OvLtxw8zfT9oLw1JSohlFzJ8jCoTgaoXvJ+kHt6fw==", "dev": true, "dependencies": { "brace-expansion": "^2.0.1" diff --git a/package.json b/package.json index 721999e..a2e6575 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "indicatorts", - "version": "2.0.0", + "version": "2.1.0", "description": "Stock technical indicators and strategies in TypeScript for browser and server programs.", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", @@ -50,14 +50,14 @@ "homepage": "https://github.com/cinar/indicatorts#readme", "devDependencies": { "@types/jest": "^29.5.12", - "@typescript-eslint/eslint-plugin": "^7.1.0", - "@typescript-eslint/parser": "^7.1.0", - "esbuild": "^0.20.1", + "@typescript-eslint/eslint-plugin": "^7.6.0", + "@typescript-eslint/parser": "^7.6.0", + "esbuild": "^0.20.2", "eslint": "^8.57.0", "eslint-config-prettier": "^9.1.0", "jest": "^29.7.0", "prettier": "^3.2.5", "ts-jest": "^29.1.2", - "typescript": "^5.3.3" + "typescript": "^5.4.5" } } diff --git a/src/backtest/index.md b/src/backtest/README.md similarity index 82% rename from src/backtest/index.md rename to src/backtest/README.md index dffb4c8..3bfce2d 100644 --- a/src/backtest/index.md +++ b/src/backtest/README.md @@ -1,16 +1,19 @@ -### Backtest +# Backtest Backtesting is the method for seeing how well a strategy would have done. The following backtesting functions are provided for evaluating strategies. -- [Strategy Info](#strategy-info) -- [Strategy Result](#strategy-result) -- [Backtest Function](#backtest-function) -- [Company Info](#company-info) -- [Company Result](#company-result) -- [Strategy Stats](#strategy-stats) - - [Compute Strategy Stats](#compute-strategy-stats) +- [Backtest](#backtest) + - [Strategy Info](#strategy-info) + - [Strategy Result](#strategy-result) + - [Backtest Function](#backtest-function) + - [Company Info](#company-info) + - [Company Result](#company-result) + - [Strategy Stats](#strategy-stats) + - [Compute Strategy Stats](#compute-strategy-stats) + - [Disclaimer](#disclaimer) + - [License](#license) -#### Strategy Info +## Strategy Info The [StrategyInfo](./strategyInfo.ts) provides a strategy function with a name. @@ -36,7 +39,7 @@ const strategyInfo: StrategyInfo = { The strategy infos for all strategies are provided under [STRATEGY_INFOS](./strategyInfo.ts). -#### Strategy Result +## Strategy Result The [StrategyResult](./strategyResult.ts) provides the result of a given strategy after the backtest. @@ -50,9 +53,9 @@ interface StrategyResult { The _info_ is the [Strategy Info](#strategy-info), the _gain_ is the result of the strategy at the end, and the _lastAction_ is the last action provided by the given strategy. -#### Backtest Function +## Backtest Function -The [backtest](./backtest.ts) function takes an [Asset](../strategy/index.md#Asset), an array of [StrategyInfo](#strategy-info), and returns an array of [StrategyResult](#strategy-result). +The [backtest](./backtest.ts) function takes an [Asset](../strategy/README.md#Asset), an array of [StrategyInfo](#strategy-info), and returns an array of [StrategyResult](#strategy-result). ```TypeScript import {bactest} from 'indicatorts'; @@ -60,7 +63,7 @@ import {bactest} from 'indicatorts'; const results = backtest(asset, STRATEGY_INFOS); ``` -#### Company Info +## Company Info The [CompanyInfo](../company/companyInfo.ts) provides the company information. @@ -75,7 +78,7 @@ interface CompanyInfo { The [SP500_COMPANIES](../company/companyInfo.ts) are provided. -#### Company Result +## Company Result The [CompanyResult](./companyResult.ts) provides the company result. @@ -88,7 +91,7 @@ interface CompanyResult { The _companyInfo_ is the [CompanyInfo](#company-info), and _strategyResults_ is an array of [StrategyResult](#strategy-result). -#### Strategy Stats +## Strategy Stats The [StrategyStats](./strategyStats.ts) provides the stats for a given strategy. @@ -104,7 +107,7 @@ interface StrategyStats { The _strategyInfo_ is the [StrategyInfo](#strategy-info) of the given strategy, _score_ is the total count of times this strategy generated the highest gain, the _minGain_ is the minimum gain, _maxGain_ is the maximum gain, and the _averageGain_ is the average gain. -##### Compute Strategy Stats +### Compute Strategy Stats The [computeStrategyStats](./strategyStats.ts) takes an array for [CompanyResult](#company-result), and returns an array of [StrategyStats](#strategy-stats). diff --git a/src/chart/index.md b/src/chart/README.md similarity index 82% rename from src/chart/index.md rename to src/chart/README.md index 2cfc4d3..1f570f6 100644 --- a/src/chart/index.md +++ b/src/chart/README.md @@ -1,14 +1,17 @@ -### Chart +# Chart Chart provides an easy way to plot the outcome of the indicators and the strategies. -- [Chart Initialization](#chart-initialization) -- [Data Set](#data-set) -- [Add Data](#add-data) -- [Remove Data](#remove-data) -- [Draw Chart](#draw-chart) +- [Chart](#chart) + - [Chart Initialization](#chart-initialization) + - [Data Set](#data-set) + - [Add Data](#add-data) + - [Remove Data](#remove-data) + - [Draw Chart](#draw-chart) + - [Disclaimer](#disclaimer) + - [License](#license) -#### Chart Initialization +## Chart Initialization The [Chart](./chart.ts) is used to draw the plot on a given canvas. @@ -22,7 +25,7 @@ import {Chart} from 'indicatorts'; const chart = new Chart('canvas'); ``` -#### Data Set +## Data Set The [DataSet](./chart.ts) interface provides the necessary information for ploting the data. @@ -37,7 +40,7 @@ export interface DataSet { The _legend_ is the legend to display for the data, the _values_ are the data values, the optional _style_ is either a single color, or an array of colors, and the optional _width_ is the width of the line. -#### Add Data +## Add Data The [add](./chart.ts) function is used to add data to the chart. @@ -50,7 +53,7 @@ chart.add({ }); ``` -#### Remove Data +## Remove Data The [remove](./chart.ts) function is used to remove data from chart by the given _legend_ value. @@ -58,7 +61,7 @@ The [remove](./chart.ts) function is used to remove data from chart by the given const removed = chart.remove(legend); ``` -#### Draw Chart +## Draw Chart The [draw](./chart.ts) function is used to draw the added data to the chart. diff --git a/src/indicator/momentum/README.md b/src/indicator/momentum/README.md new file mode 100644 index 0000000..81f17b2 --- /dev/null +++ b/src/indicator/momentum/README.md @@ -0,0 +1,203 @@ +# Momentum Indicators + +Momentum indicators measure the speed of movement. + +- [Momentum Indicators](#momentum-indicators) + - [Awesome Oscillator (AO)](#awesome-oscillator-ao) + - [Chaikin Oscillator (CMO)](#chaikin-oscillator-cmo) + - [Ichimoku Cloud](#ichimoku-cloud) + - [Percentage Price Oscillator (PPO)](#percentage-price-oscillator-ppo) + - [Percentage Volume Oscillator (PVO)](#percentage-volume-oscillator-pvo) + - [Price Rate of Change (ROC)](#price-rate-of-change-roc) + - [Relative Strength Index (RSI)](#relative-strength-index-rsi) + - [Stochastic Oscillator (STOCH)](#stochastic-oscillator-stoch) + - [Williams R (WILLR)](#williams-r-willr) + - [Disclaimer](#disclaimer) + - [License](#license) + +**NOTE:** All configuration objects for all indicators are optional. If no configuration object is passed, the default configuration will be used. Likewise, you may also partially pass a configuration object, and the default values will be used for the missing properties. + +## Awesome Oscillator (AO) + +The [awesomeOscillator](./awesomeOscillator.ts) function calculates the awesome oscillator based on low and high daily prices for a given stock. It is an indicator used to measure market momentum. + +``` +Median Price = ((Low + High) / 2) +AO = 5-Period SMA - 34-Period SMA. +``` + +```TypeScript +import { ao } from 'indicatorts'; + +const defaultConfig = { fast: 5, slow: 34 }; +const result = ao(highs, lows, defaultConfig); + +// Alternatively: +// const result = awesomeOscillator(highs, lows, defaultConfig); +``` + +## Chaikin Oscillator (CMO) + +The [chaikinOscillator](./chaikinOscillator.ts) function measures the momentum of the [Accumulation/Distribution (A/D)](../volume/README.md#accumulationdistribution-ad) using the [Moving Average Convergence Divergence (MACD)](../trend/README.md#moving-average-convergence-divergence-macd) formula. It takes the difference between fast and slow periods EMA of the A/D. Cross above the A/D line indicates bullish. + +``` +CO = Ema(fastPeriod, AD) - Ema(slowPeriod, AD) +``` + +```TypeScript +import { cmo } from 'indicatorts'; + +const defaultConfig = { fast: 3, slow: 10 }; +const { adResult, cmoResult } = cmo(highs, lows, closings, volumes, defaultConfig); + +// Alternatively: +// const { adResult, cmoResult } = chaikinOscillator(highs, lows, closings, volumes, defaultConfig); +``` + +Most frequently used fast and short periods are 3 and 10. + +## Ichimoku Cloud + +The [ichimokuCloud](./ichimokuCloud.ts), also known as Ichimoku Kinko Hyo, calculates a versatile indicator that defines support and resistence, identifies trend direction, gauges momentum, and provides trading signals. + +``` +Tenkan-sen (Conversion Line) = (9-Period High + 9-Period Low) / 2 +Kijun-sen (Base Line) = (26-Period High + 26-Period Low) / 2 +Senkou Span A (Leading Span A) = (Conversion Line + Base Line) / 2 +Senkou Span B (Leading Span B) = (52-Period High + 52-Period Low) / 2 +Chikou Span (Lagging Span) = Closing plotted 26 days in the past. +``` + +```TypeScript +import { ichimokuCloud } from 'indicatorts'; + +const defaultConfig = { short: 9, medium: 26, long: 52, close: 26 }; +const { conversion, base, leadingSpanA, leadingSpanB, leadingSpan } = ichimokuCloud(highs, lows, closings, defaultConfig); +``` + +## Percentage Price Oscillator (PPO) + +The [percentagePriceOscillator](./percentagePriceOscillator.ts) function calculates a momentum oscillator for the price It is used to indicate the ups and downs based on the price. A breakout is confirmed when PPO is positive. + +``` +PPO = ((EMA(fastPeriod, prices) - EMA(slowPeriod, prices)) / EMA(longPeriod, prices)) * 100 +Signal = EMA(9, PPO) +Histogram = PPO - Signal +``` + +```TypeScript +import { ppo } from 'indicatorts'; + +const defaultConfig = { fast: 12, slow: 26, signal: 9 }; +const { ppoResult, signal, histogram } = ppo(prices, defaultConfig); + +// Alternatively: +// const { ppoResult, signal, histogram } = percentagePriceOscillator(prices, defaultConfig); +``` + +## Percentage Volume Oscillator (PVO) + +The [percentageVolumeOscillator](./percentageVolumeOscillator.ts) function calculates a momentum oscillator for the volume It is used to indicate the ups and downs based on the volume. A breakout is confirmed when PVO is positive. + +``` +PVO = ((EMA(fastPeriod, volumes) - EMA(slowPeriod, volumes)) / EMA(longPeriod, volumes)) * 100 +Signal = EMA(9, PVO) +Histogram = PVO - Signal +``` + +```TypeScript +import { pvo } from 'indicatorts'; + +const defaultConfig = { fast: 12, slow: 26, signal: 9 }; +const { pvoResult, signal, histogram } = pvo(volumes, defaultConfig); + +// Alternatively: +// const { pvoResult, signal, histogram } = percentageVolumeOscillator(volumes, defaultConfig); +``` + +## Price Rate of Change (ROC) + +The [roc](./priceRateOfChange.ts) function calculates a unbounded momentum indicator for the closing prices. A rising ROC above zero typically indicates an uptrend whereas a falling ROC below zero indicates a downtrend. + +``` +ROC[i] = 0 when i < period +ROC[i] = (close[i] / close[i-period] - 1) * 100 when i >= period +``` + +```TypeScript +import { roc } from 'indicatorts'; + +const defaultConfig = { period: 3 }; +const result = roc(close, defaultConfig); + +// Alternatively: +// const result = priceRateOfChange(close, defaultConfig); +``` + +Ensure that the array `close` does not contain $0$ to avoid division by 0 errors. + +## Relative Strength Index (RSI) + +The [rsi](./relativeStrengthIndex.ts) function calculates a momentum indicator that measures the magnitude of recent price changes to evaluate overbought and oversold conditions using a window period. + +``` +RS = Average Gain / Average Loss +RSI = 100 - (100 / (1 + RS)) +``` + +```TypeScript +import { rsi } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const result = rsi(closings, defaultConfig); + +// Alternatively: +// const result = relativeStrengthIndex(closings, defaultConfig); +``` + +## Stochastic Oscillator (STOCH) + +The [stochasticOscillator](./stochasticOscillator.ts) function calculates a momentum indicator that shows the location of the closing relative to high-low range over a set number of periods. + +``` +K = (Closing - Lowest Low) / (Highest High - Lowest Low) * 100 +D = 3-Period SMA of K +``` + +```TypeScript +import { stoch } from 'indicatorts'; + +const defaultConfig = { kPeriod: 14, dPeriod: 3 }; +const { k, d } = stoch(highs, lows, closings, defaultConfig); + +// Alternatively: +// const { k, d } = stochasticOscillator(highs, lows, closings, defaultConfig); +``` + +## Williams R (WILLR) + +The [williamsR](./williamsR.ts) function calculates the Williams R based on low, high, and closing prices. It is a type of momentum indicator that moves between 0 and -100 and measures overbought and oversold levels. + +``` +WR = (Highest High - Closing) / (Highest High - Lowest Low) +``` + +```TypeScript +import { willr } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const result = willr(highs, lows, closings, defaultConfig); + +// Alternatively: +// const result = williamsR(highs, lows, closings, defaultConfig); +``` + +## Disclaimer + +The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. + +## License + +Copyright (c) 2022 Onur Cinar. All Rights Reserved. + +The source code is provided under MIT License. diff --git a/src/indicator/momentum/chaikinOscillator.test.ts b/src/indicator/momentum/chaikinOscillator.test.ts index ed8abd7..c02ea02 100644 --- a/src/indicator/momentum/chaikinOscillator.test.ts +++ b/src/indicator/momentum/chaikinOscillator.test.ts @@ -23,8 +23,8 @@ describe('Chaikin Oscillator (CMO)', () => { fast: 2, slow: 5, }); - deepStrictEqual(roundDigitsAll(2, actual.ad), expectedAD); - deepStrictEqual(roundDigitsAll(2, actual.cmo), expectedCMO); + deepStrictEqual(roundDigitsAll(2, actual.adResult), expectedAD); + deepStrictEqual(roundDigitsAll(2, actual.cmoResult), expectedCMO); }); it('should be able to compute without a config', () => { @@ -36,7 +36,7 @@ describe('Chaikin Oscillator (CMO)', () => { ]; const actual = cmo(highs, lows, closings, volumes); - deepStrictEqual(roundDigitsAll(2, actual.ad), expectedAD); - deepStrictEqual(roundDigitsAll(2, actual.cmo), expectedCMO); + deepStrictEqual(roundDigitsAll(2, actual.adResult), expectedAD); + deepStrictEqual(roundDigitsAll(2, actual.cmoResult), expectedCMO); }); }); diff --git a/src/indicator/momentum/chaikinOscillator.ts b/src/indicator/momentum/chaikinOscillator.ts index ef9f881..f2c1756 100644 --- a/src/indicator/momentum/chaikinOscillator.ts +++ b/src/indicator/momentum/chaikinOscillator.ts @@ -9,8 +9,8 @@ import { ad } from '../volume/accumulationDistribution'; * Chaikin oscillator result object. */ export interface CMOResult { - ad: number[]; - cmo: number[]; + adResult: number[]; + cmoResult: number[]; } /** @@ -59,7 +59,7 @@ export function cmo( ema(adResult, { period: slow }) ); - return { ad: adResult, cmo: cmoResult }; + return { adResult, cmoResult }; } // Export full name diff --git a/src/indicator/momentum/index.md b/src/indicator/momentum/index.md deleted file mode 100644 index 2cd11a2..0000000 --- a/src/indicator/momentum/index.md +++ /dev/null @@ -1,233 +0,0 @@ -### Momentum Indicators - -Momentum indicators measure the speed of movement. - -- [Awesome Oscillator](#awesome-oscillator) -- [Chaikin Oscillator](#chaikin-oscillator) -- [Custom RSI](#custom-rsi) -- [Ichimoku Cloud](#ichimoku-cloud) -- [Percentage Price Oscillator (PPO)](#percentage-price-oscillator-ppo) -- [Percentage Volume Oscillator (PVO)](#percentage-volume-oscillator-pvo) -- [Price Rate of CHange (ROC)](#price-rate-of-change-roc) -- [Relative Strength Index (RSI)](#relative-strength-index-rsi) -- [RSI 2](#rsi-2) -- [Stochastic Oscillator](#stochastic-oscillator) -- [Williams R](#williams-r) - -#### Awesome Oscillator - -The [awesomeOscillator](./awesomeOscillator.ts) function calculates the awesome oscillator based on low and high daily prices for a given stock. It is an indicator used to measure market momentum. - -``` -Median Price = ((Low + High) / 2) -AO = 5-Period SMA - 34-Period SMA. -``` - -```TypeScript -import {awesomeOscillator} from 'indicatorts'; - -const optionalConfig = { fast: 5, slow: 34 }; -const result = awesomeOscillator(highs, lows, optionalConfig); -``` - -#### Chaikin Oscillator - -The [chaikinOscillator](./chaikinOscillator.ts) function measures the momentum of the [Accumulation/Distribution (A/D)](../volume/index.md#accumulationdistribution-ad) using the [Moving Average Convergence Divergence (MACD)](../trend/index.md#moving-average-convergence-divergence-macd) formula. It takes the difference between fast and slow periods EMA of the A/D. Cross above the A/D line indicates bullish. - -``` -CO = Ema(fastPeriod, AD) - Ema(slowPeriod, AD) -``` - -```TypeScript -import {chaikinOscillator} from 'indicatorts'; - -const optionalConfig = { fast: 3, slow: 10 }; -const result = chaikinOscillator(highs, lows, closings, volumes, optionalConfig); -``` - -Most frequently used fast and short periods are 3 and 10. - -#### RSI - -The [customRsi](./rsi.ts) function calculates Relative Strength Index (RSI), a momentum indicator that measures the magnitude of recent price changes to evaluate overbought and oversold conditions using the given window period. - -``` -RS = Average Gain / Average Loss -RSI = 100 - (100 / (1 + RS)) -``` - -```TypeScript -import {rsi} from 'indicatorts'; - -const result = rsi(closings, { period: 14 }); -``` - -#### Ichimoku Cloud - -The [ichimokuCloud](./ichimokuCloud.ts), also known as Ichimoku Kinko Hyo, calculates a versatile indicator that defines support and resistence, identifies tred direction, gauges momentum, and provides trading signals. - -``` -Tenkan-sen (Conversion Line) = (9-Period High + 9-Period Low) / 2 -Kijun-sen (Base Line) = (26-Period High + 26-Period Low) / 2 -Senkou Span A (Leading Span A) = (Conversion Line + Base Line) / 2 -Senkou Span B (Leading Span B) = (52-Period High + 52-Period Low) / 2 -Chikou Span (Lagging Span) = Closing plotted 26 days in the past. -``` - -```TypeScript -import {ichimokuCloud} from 'indicatorts'; - -const result = ichimokuCloud( - highs, - lows, - closings, - { - short: 9, - medium: 26, - long: 52, - close: 26, - } -); -``` - -#### Percentage Price Oscillator (PPO) - -The [percentagePriceOscillator](./percentagePriceOscillator.ts) function calculates a momentum oscillator for the price It is used to indicate the ups and downs based on the price. A breakout is confirmed when PPO is positive. - -``` -PPO = ((EMA(fastPeriod, prices) - EMA(slowPeriod, prices)) / EMA(longPeriod, prices)) * 100 -Signal = EMA(9, PPO) -Histogram = PPO - Signal -``` - -```TypeScript -import {percentagePriceOscillator} from 'indicatorts'; - -const result = percentagePriceOscillator( - fastPeriod, - slowPeriod, - signalPeriod, - prices -); -``` - -The [defaultPercentagePriceOscillator](./percentagePriceOscillator.ts) function calculates it with the default periods of 12, 26, 9. - -```TypeScript -import {defaultPercentagePriceOscillator} from 'indicatorts'; - -const result = defaultPercentagePriceOscillator(prices); -``` - -#### Percentage Volume Oscillator (PVO) - -The [percentageVolumeOscillator](./percentageVolumeOscillator.ts) function calculates a momentum oscillator for the volume It is used to indicate the ups and downs based on the volume. A breakout is confirmed when PVO is positive. - -``` -PVO = ((EMA(fastPeriod, volumes) - EMA(slowPeriod, volumes)) / EMA(longPeriod, volumes)) * 100 -Signal = EMA(9, PVO) -Histogram = PVO - Signal -``` - -```TypeScript -import {percentageVolumeOscillator} from 'indicatorts'; - -const result = percentageVolumeOscillator( - fastPeriod, - slowPeriod, - signalPeriod, - volumes -); -``` - -The [defaultPercentageVolumeOscillator](./percentageVolumeOscillator.ts) function calculates it with the default periods of 12, 26, 9. - -```TypeScript -import {defaultPercentageVolumeOscillator} from 'indicatorts'; - -const result = defaultPercentageVolumeOscillator(volumes); -``` - -#### Price Rate of Change (ROC) - -The [roc](./priceRateOfChange.ts) function calculates a unbounded momentum indicator for the closing prices. A rising ROC above zero typically indicates an uptrend whereas a falling ROC below zero indicates a downtrend. - -``` -ROC[i] = 0 when i < period -ROC[i] = (close[i] / close[i-period] - 1) * 100 when i >= period -``` - -```TypeScript -import {roc} from 'indicatorts'; - -const result = roc( - period, - close -); -``` - -Ensure that the array `close` does not contain $0$ to avoid division by 0 errors. - -#### Relative Strength Index (RSI) - -The [rsi](./rsi.ts) function calculates a momentum indicator that measures the magnitude of recent price changes to evaluate overbought and oversold conditions using the window period of 14. - -``` -RS = Average Gain / Average Loss -RSI = 100 - (100 / (1 + RS)) -``` - -```TypeScript -import {rsi} from 'indicatorts'; - -const result = rsi(closings); -``` - -#### RSI 2 - -The [rsi2](./rsi2.ts) function calculates a RSI with 2 period that provides a mean-reversion trading strategy. It is developed by Larry Connors. - -```TypeScript -import {rsi2} from 'indicatorts'; - -const result = rsi2(closings); -``` - -#### Stochastic Oscillator - -The [stochasticOscillator](./stochasticOscillator.ts) function calculates a momentum indicator that shows the location of the closing relative to high-low range over a set number of periods. - -``` -K = (Closing - Lowest Low) / (Highest High - Lowest Low) * 100 -D = 3-Period SMA of K -``` - -```TypeScript -import {stochasticOscillator} from 'indicatorts'; - -const result = stochasticOscillator(highs, lows, closings); -``` - -#### Williams R - -The [williamsR](./williamsR.ts) function calculates the Williams R based on low, high, and closing prices. It is a type of momentum indicator that moves between 0 and -100 and measures overbought and oversold levels. - -``` -WR = (Highest High - Closing) / (Highest High - Lowest Low) -``` - -```TypeScript -import {williamsR} from 'indicatorts'; - -const result = williamsR(highs, lows, closings); -``` - -## Disclaimer - -The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. - -## License - -Copyright (c) 2022 Onur Cinar. All Rights Reserved. - -The source code is provided under MIT License. diff --git a/src/indicator/momentum/percentagePriceOscillator.test.ts b/src/indicator/momentum/percentagePriceOscillator.test.ts index acd3b83..8e94873 100644 --- a/src/indicator/momentum/percentagePriceOscillator.test.ts +++ b/src/indicator/momentum/percentagePriceOscillator.test.ts @@ -61,7 +61,7 @@ describe('Percent Price Oscillator (PPO)', () => { signal: 7, }); - deepStrictEqual(roundDigitsAll(2, actual.ppo), expectedPPO); + deepStrictEqual(roundDigitsAll(2, actual.ppoResult), expectedPPO); deepStrictEqual(roundDigitsAll(2, actual.signal), expectedSignal); deepStrictEqual(roundDigitsAll(2, actual.histogram), expectedHistogram); }); @@ -101,7 +101,7 @@ describe('Percent Price Oscillator (PPO)', () => { ]; const actual = ppo(prices); - deepStrictEqual(roundDigitsAll(2, actual.ppo), expectedPPO); + deepStrictEqual(roundDigitsAll(2, actual.ppoResult), expectedPPO); deepStrictEqual(roundDigitsAll(2, actual.signal), expectedSignal); deepStrictEqual(roundDigitsAll(2, actual.histogram), expectedHistogram); }); diff --git a/src/indicator/momentum/percentagePriceOscillator.ts b/src/indicator/momentum/percentagePriceOscillator.ts index b8bc5c6..56cec22 100644 --- a/src/indicator/momentum/percentagePriceOscillator.ts +++ b/src/indicator/momentum/percentagePriceOscillator.ts @@ -8,7 +8,7 @@ import { ema } from '../trend/exponentialMovingAverage'; * Percentage price oscillator result. */ export interface PPOResult { - ppo: number[]; + ppoResult: number[]; signal: number[]; histogram: number[]; } @@ -53,12 +53,15 @@ export function ppo(prices: number[], config: PPOConfig = {}): PPOResult { const fastEma = ema(prices, { period: fastPeriod }); const slowEma = ema(prices, { period: slowPeriod }); - const ppo = multiplyBy(100, divide(subtract(fastEma, slowEma), slowEma)); - const signal = ema(ppo, { period: signalPeriod }); - const histogram = subtract(ppo, signal); + const ppoResult = multiplyBy( + 100, + divide(subtract(fastEma, slowEma), slowEma) + ); + const signal = ema(ppoResult, { period: signalPeriod }); + const histogram = subtract(ppoResult, signal); return { - ppo, + ppoResult, signal, histogram, }; diff --git a/src/indicator/momentum/percentageVolumeOscillator.test.ts b/src/indicator/momentum/percentageVolumeOscillator.test.ts index 3c8f38c..cc7ed6a 100644 --- a/src/indicator/momentum/percentageVolumeOscillator.test.ts +++ b/src/indicator/momentum/percentageVolumeOscillator.test.ts @@ -59,7 +59,7 @@ describe('Percent Volume Oscillator (PVO)', () => { signal: 7, }); - deepStrictEqual(roundDigitsAll(2, actual.pvo), expectedPVO); + deepStrictEqual(roundDigitsAll(2, actual.pvoResult), expectedPVO); deepStrictEqual(roundDigitsAll(2, actual.signal), expectedSignal); deepStrictEqual(roundDigitsAll(2, actual.histogram), expectedHistogram); }); @@ -101,7 +101,7 @@ describe('Percent Volume Oscillator (PVO)', () => { ]; const actual = pvo(volumes); - deepStrictEqual(roundDigitsAll(2, actual.pvo), expectedPVO); + deepStrictEqual(roundDigitsAll(2, actual.pvoResult), expectedPVO); deepStrictEqual(roundDigitsAll(2, actual.signal), expectedSignal); deepStrictEqual(roundDigitsAll(2, actual.histogram), expectedHistogram); }); diff --git a/src/indicator/momentum/percentageVolumeOscillator.ts b/src/indicator/momentum/percentageVolumeOscillator.ts index d84967c..cea1e82 100644 --- a/src/indicator/momentum/percentageVolumeOscillator.ts +++ b/src/indicator/momentum/percentageVolumeOscillator.ts @@ -8,7 +8,7 @@ import { ema } from '../trend/exponentialMovingAverage'; * Percentage volume oscillator result. */ export interface PVOResult { - pvo: number[]; + pvoResult: number[]; signal: number[]; histogram: number[]; } @@ -53,12 +53,15 @@ export function pvo(volumes: number[], config: PVOConfig = {}): PVOResult { const fastEma = ema(volumes, { period: fastPeriod }); const slowEma = ema(volumes, { period: slowPeriod }); - const pvo = multiplyBy(100, divide(subtract(fastEma, slowEma), slowEma)); - const signal = ema(pvo, { period: signalPeriod }); - const histogram = subtract(pvo, signal); + const pvoResult = multiplyBy( + 100, + divide(subtract(fastEma, slowEma), slowEma) + ); + const signal = ema(pvoResult, { period: signalPeriod }); + const histogram = subtract(pvoResult, signal); return { - pvo, + pvoResult, signal, histogram, }; diff --git a/src/indicator/momentum/priceRateOfChange.ts b/src/indicator/momentum/priceRateOfChange.ts index 6d0bbab..1479f46 100644 --- a/src/indicator/momentum/priceRateOfChange.ts +++ b/src/indicator/momentum/priceRateOfChange.ts @@ -17,6 +17,10 @@ export const ROCDefaultConfig: Required = { /** * Price Rate of Change (ROC). + * + * ROC[i] = 0 when i < period + * ROC[i] = (close[i] / close[i-period] - 1) * 100 when i >= period + * * @param values values array. * @return ROC values. */ diff --git a/src/indicator/momentum/relativeStrengthIndex.ts b/src/indicator/momentum/relativeStrengthIndex.ts index f47679c..2729800 100644 --- a/src/indicator/momentum/relativeStrengthIndex.ts +++ b/src/indicator/momentum/relativeStrengthIndex.ts @@ -63,3 +63,6 @@ export function rsi(closings: number[], config: RSIConfig = {}): number[] { return rValue; } + +// Export full name +export { rsi as relativeStrengthIndex }; diff --git a/src/indicator/trend/README.md b/src/indicator/trend/README.md new file mode 100644 index 0000000..9cc5384 --- /dev/null +++ b/src/indicator/trend/README.md @@ -0,0 +1,517 @@ +# Trend Indicators + +Trend indicators measure the direction and strength of a trend. + +- [Trend Indicators](#trend-indicators) + - [Absolute Price Oscillator (APO)](#absolute-price-oscillator-apo) + - [Aroon](#aroon) + - [Balance of Power (BOP)](#balance-of-power-bop) + - [Chande Forecast Oscillator (CFO)](#chande-forecast-oscillator-cfo) + - [Community Channel Index (CCI)](#community-channel-index-cci) + - [Double Exponential Moving Average (DEMA)](#double-exponential-moving-average-dema) + - [Exponential Moving Average (EMA)](#exponential-moving-average-ema) + - [Mass Index (MI)](#mass-index-mi) + - [Moving Average Convergence Divergence (MACD)](#moving-average-convergence-divergence-macd) + - [Moving Max (MMAX)](#moving-max-mmax) + - [Moving Min (MMIN)](#moving-min-mmin) + - [Moving Sum (MSUM)](#moving-sum-msum) + - [Parabolic SAR (PSAR)](#parabolic-sar-psar) + - [Qstick](#qstick) + - [Random Index (KDJ)](#random-index-kdj) + - [Rolling Moving Average (RMA)](#rolling-moving-average-rma) + - [Simple Moving Average (SMA)](#simple-moving-average-sma) + - [Since Change](#since-change) + - [Triple Exponential Moving Average (TEMA)](#triple-exponential-moving-average-tema) + - [Triangular Moving Average (TRIMA)](#triangular-moving-average-trima) + - [Triple Exponential Average (TRIX)](#triple-exponential-average-trix) + - [Typical Price](#typical-price) + - [Volume Weighted Moving Average (VWMA)](#volume-weighted-moving-average-vwma) + - [Vortex Indicator](#vortex-indicator) + - [Disclaimer](#disclaimer) + - [License](#license) + +**NOTE:** All configuration objects for all indicators are optional. If no configuration object is passed, the default configuration will be used. Likewise, you may also partially pass a configuration object, and the default values will be used for the missing properties. + +## Absolute Price Oscillator (APO) + +The [absolutePriceOscillator](./absolutePriceOscillator.ts) function calculates a technical indicator that is used to follow trends. APO crossing above zero indicates bullish, while crossing below zero indicates bearish. Positive value is upward trend, while negative value is downward trend. + +``` +Fast = Ema(fastPeriod, values) +Slow = Ema(slowPeriod, values) +APO = Fast - Slow +``` + +```TypeScript +import { apo } from 'indicatorts'; + +const defaultConfig = { fast: 14, slow: 30 }; +const result = apo(values, defaultConfig); + +// Alternatively: +// const result = absolutePriceOscillator(values, defaultConfig); +``` + +## Aroon + +The [Aroon](./aroon.ts) function calculates a technical indicator that is used to identify trend changes in the price of a stock, as well as the strength of that trend. It consists of two lines, Aroon Up, and Aroon Down. The Aroon Up line measures measures the strength of the uptrend, and the Aroon Down measures the strength of the downtrend. When Aroon Up is above Aroon Down, it indicates bullish price, and when Aroon Down is above Aroon Up, it indicates bearish price. + +``` +Aroon Up = ((25 - Period Since Last 25 Period High) / 25) * 100 +Aroon Down = ((25 - Period Since Last 25 Period Low) / 25) * 100 +``` + +```TypeScript +import { aroon } from 'indicatorts'; + +const defaultConfig = { period: 25 }; +const { up, down } = aroon(highs, lows, defaultConfig); +``` + +## Balance of Power (BOP) + +The [BalanceOfPower](./balanceOfPower.ts) function calculates the strength of buying and selling pressure. Positive value indicates an upward trend, and negative value indicates a downward trend. Zero indicates a balance between the two. + +``` +BOP = (Closing - Opening) / (High - Low) +``` + +```Typescript +import { bop } from 'indicatorts'; + +const result = bop(openings, highs, lows, closings); + +// Alternatively: +// const result = balanceOfPower(openings, highs, lows, closings); +``` + +## Chande Forecast Oscillator (CFO) + +The [chandeForecastOscillator](./chandeForecastOscillator.ts) developed by Tushar Chande The Forecast Oscillator plots the percentage difference between the closing price and the n-period linear regression forecasted price. The oscillator is above zero when the forecast price is greater than the closing price and less than zero if it is below. + +``` +R = Linreg(Closing) +CFO = ((Closing - R) / Closing) * 100 +``` + +Based on [Chande Forecast Oscillator Formula, Strategy](https://www.stockmaniacs.net/chande-forecast-oscillator/), [Forecast Oscillator +](https://www.fmlabs.com/reference/default.htm?url=ForecastOscillator.htm), and [Least Squares Regression](https://www.mathsisfun.com/data/least-squares-regression.html). + +```TypeScript +import { cfo } from 'indicatorts'; + +const result = cfo(closings); + +// Alternatively: +// const result = chandeForecastOscillator(closings); +``` + +There is also an oscillator for calculating the moving chande forecast oscillator. + +```TypeScript +import { mfco } from 'indicatorts'; + +const defaultConfig = { period: 4 }; +const result = mfco(closings, defaultConfig); + +// Alternatively: +// const result = movingChandeForecastOscillator(closings, defaultConfig); +``` + +## Community Channel Index (CCI) + +The [communityChannelIndex](./communityChannelIndex.ts) is a momentum-based oscillator used to help determine when an investment vehicle is reaching a condition of being overbought or oversold. + +``` +Moving Average = Sma(Period, Typical Price) +Mean Deviation = Sma(Period, Abs(Typical Price - Moving Average)) +CMI = (Typical Price - Moving Average) / (0.015 * Mean Deviation) +``` + +```TypeScript +import { cci } from 'indicatorts'; + +const defaultConfig = { period: 20 }; +const result = cci(highs, lows, closings, defaultConfig); + +// Alternatively: +// const result = communityChannelIndex(highs, lows, closings, defaultConfig); +``` + +## Double Exponential Moving Average (DEMA) + +The [dema](./doubleExponentialMovingAverage.ts) function calculates the Double Exponential Moving Average (DEMA) for a given period. + +The double exponential moving average (DEMA) is a technical indicator introduced by Patrick Mulloy. The purpose is to reduce the amount of noise present in price charts used by technical traders. The DEMA uses two exponential moving averages (EMAs) to eliminate lag. It helps confirm uptrends when the price is above the average, and helps confirm downtrends when the price is below the average. When the price crosses the average that may signal a trend change. + +``` +DEMA = (2 * EMA(values)) - EMA(EMA(values)) +``` + +```TypeScript +import { dema } from 'indicatorts'; + +const defaultConfig = { period: 12 }; +const result = dema(values, defaultConfig); + +// Alternatively: +// const result = doubleExponentialMovingAverage(values, defaultConfig); +``` + +Based on [Double Exponential Moving Average (DEMA)](https://www.investopedia.com/terms/d/double-exponential-moving-average.asp). + +## Exponential Moving Average (EMA) + +The [ema](./exponentialMovingAverage.ts) function calculates the exponential moving average for a given period. + +```TypeScript +import { ema } from 'indicatorts'; + +const defaultConfig = { period: 12 }; +const result = ema(values, defaultConfig); + +// Alternatively: +// const result = exponentialMovingAverage(values, defaultConfig); +``` + +## Mass Index (MI) + +The [massIndex](./massIndex.ts) uses the high-low range to identify trend reversals based on range expansions. + +``` +Singe EMA = EMA(9, Highs - Lows) +Double EMA = EMA(9, Single EMA) +Ratio = Single EMA / Double EMA +MI = Sum(25, Ratio) +``` + +```TypeScript +import { mi } from 'indicatorts'; + +const defaultConfig = { emaPeriod: 9, miPeriod: 25 }; +const result = mi(highs, lows, defaultConfig); + +// Alternatively: +// const result = massIndex(highs, lows, defaultConfig); +``` + +## Moving Average Convergence Divergence (MACD) + +The [macd](./movingAverageConvergenceDivergence.ts) function calculates a trend-following momentum indicator that shows the relationship between two moving averages of price. + +``` +MACD = 12-Period EMA - 26-Period EMA. +Signal = 9-Period EMA of MACD. +``` + +```TypeScript +import { macd } from 'indicatorts'; + +const defaultConfig = { fast: 12, slow: 26, signal: 9 }; +const { macdLine, signalLine } = macd(closings); + +// Alternatively: +// const { macdLine, signalLine } = movingAverageConvergenceDivergence(closings, defaultConfig); +``` + +## Moving Max (MMAX) + +The [mmax](./movingMax.ts) function gives the maximum value within the given moving period. It can be used to get the moving maximum closing price and other values. + +```TypeScript +import { mmax } from 'indicatorts'; + +const defaultConfig = { period: 4 }; +const result = mmax(values, defaultConfig); + +// Alternatively: +// const result = movingMax(values, defaultConfig); +``` + +## Moving Min (MMIN) + +The [mmin](./movingMin.ts) function gives the minimum value within the given moving period. It can be used to get the moving minimum closing price and other values. + +```TypeScript +import { mmin } from 'indicatorts'; + +const defaultConfig = { period: 4 }; +const result = mmin(values, defaultConfig); + +// Alternatively: +// const result = movingMin(values, defaultConfig); +``` + +## Moving Sum (MSUM) + +The [msum](./movingSum.ts) function gives the sum value within the given moving period. + +```TypeScript +import { msum } from 'indicatorts'; + +const defaultConfig = { period: 4 }; +const result = msum(values, defaultConfig); + +// Alternatively: +// const result = movingSum(values, defaultConfig); +``` + +## Parabolic SAR (PSAR) + +The [parabolicSar](./parabolicSar.ts) function calculates an identifier for the trend and the trailing stop. + +``` +PSAR = PSAR[i - 1] - ((PSAR[i - 1] - EP) * AF) +``` + +If the trend is Falling: + +- PSAR is the maximum of PSAR or the previous two high values. +- If the current high is greather than or equals to PSAR, use EP. + +If the trend is Rising: + +- PSAR is the minimum of PSAR or the previous two low values. +- If the current low is less than or equials to PSAR, use EP. + +If PSAR is greather than the closing, trend is falling, and the EP is set to the minimum of EP or the low. + +If PSAR is lower than or equals to the closing, trend is rising, and the EP is set to the maximum of EP or the high. + +If the trend is the same, and AF is less than 0.20, increment it by 0.02. If the trend is not the same, set AF to 0.02. + +Based on video [How to Calculate the PSAR Using Excel - Revised Version](https://www.youtube.com/watch?v=MuEpGBAH7pw&t=0s). + +```TypeScript +import { psar } from 'indicatorts'; + +const defaultConfig = { step: 0.02, max: 0.2 }; +const { trends, psarResult } = psar(highs, lows, closings, defaultConfig); + +// Alternatively: +// const { trends, psarResult } = parabolicSar(highs, lows, closings, defaultConfig); +``` + +## Qstick + +The [qstick](./qstick.ts) function calculates the ratio of recent up and down bars. + +``` +QS = Sma(Closing - Opening) +``` + +```TypeScript +import { qstick } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const result = qstick(openings, closings, defaultConfig); +``` + +## Random Index (KDJ) + +The [kdj](./randomIndex.ts) function calculates the KDJ indicator, also known as the Random Index. KDJ is calculated similar to the Stochastic Oscillator with the difference of having the J line. It is used to analyze the trend and entry points. + +The K and D lines show if the asset is overbought when they crosses above 80%, and oversold when they crosses below 20%. The J line represents the divergence. + +``` +RSV = ((Closing - Min(Low, rPeriod)) / (Max(High, rPeriod) - Min(Low, rPeriod))) * 100 +K = Sma(RSV, kPeriod) +D = Sma(K, dPeriod) +J = (3 * K) - (2 * D) +``` + +```TypeScript +import { kdj } from 'indicatorts'; + +const defaultConfig = { rPeriod: 9, kPeriod: 3, dPeriod: 3 }; +const { k, d, j } = kdj(highs, lows, closings, defaultConfig); + +// Alternatively: +// const { k, d, j } = randomIndex(highs, lows, closings, defaultConfig); +``` + +## Rolling Moving Average (RMA) + +The [rma](./rollingMovingAverage.ts) function calculates the rolling moving average for a given period. + +``` +R[0] to R[p-1] is SMA(values) +R[p] and after is R[i] = ((R[i-1]*(p-1)) + v[i]) / p +``` + +```TypeScript +import { rma } from 'indicatorts'; + +const defaultConfig = { period: 4 }; +const result = rma(values, defaultConfig); + +// Alternatively: +// const result = rollingMovingAverage(values, defaultConfig); +``` + +## Simple Moving Average (SMA) + +The [sma](./simpleMovingAverage.ts) function calculates the simple moving average for a given period. + +```TypeScript +import { sma } from 'indicatorts'; + +const defaultConfig = { period: 2 }; +const result = sma(values); + +// Alternatively: +// const result = simpleMovingAverage(values, defaultConfig); +``` + +## Since Change + +The [since](./since.ts) function provides the number values since the last change. + +```TypeScript +import { since } from 'indicatorts'; + +const result = since(values); +``` + +## Triple Exponential Moving Average (TEMA) + +The [tema](./tripleExponentialMovingAverage.ts) function calculates the Triple Exponential Moving Average (TEMA) for a given period. + +The triple exponential moving average (TEMA) was designed to smooth value fluctuations, thereby making it easier to identify trends without the lag associated with traditional moving averages. It does this by taking multiple exponential moving averages (EMA) of the original EMA and subtracting out some of the lag. + +``` +TEMA = (3 * EMA1) - (3 * EMA2) + EMA3 +EMA1 = EMA(values) +EMA2 = EMA(EMA1) +EMA3 = EMA(EMA2) +``` + +```TypeScript +import { tema } from 'indicatorts'; + +const defaultConfig = { period: 2 }; +const result = tema(values, defaultConfig); + +// Alternatively: +// const result = tripleExponentialMovingAverage(values, defaultConfig); +``` + +Based on [Triple Exponential Moving Average (TEMA)](https://www.investopedia.com/terms/t/triple-exponential-moving-average.asp). + +## Triangular Moving Average (TRIMA) + +The [trima](./triangularMovingAverage.ts) function calculates the Triangular Moving Average (TRIMA) for a given period. + +The Triangular Moving Average (TRIMA) is a weighted moving average putting more weight to the middle values. + +``` +If period is even: + TRIMA = SMA(period / 2, SMA((period / 2) + 1, values)) +If period is odd: + TRIMA = SMA((period + 1) / 2, SMA((period + 1) / 2, values)) +``` + +```TypeScript +import { trima } from 'indicatorts'; + +const defaultConfig = { period: 4 }; +const result = trima(values, defaultConfig); + +// Alternatively: +// const result = triangularMovingAverage(values, defaultConfig); +``` + +Based on [Triangular Moving Average](https://tulipindicators.org/trima). + +## Triple Exponential Average (TRIX) + +The [trix](./tripleExponentialAverage.ts) indicator is an oscillator used to identify oversold and overbought markets, and it can also be used as a momentum indicator. Like many oscillators, TRIX oscillates around a zero line. + +``` +EMA1 = EMA(period, values) +EMA2 = EMA(period, EMA1) +EMA3 = EMA(period, EMA2) +TRIX = (EMA3 - Previous EMA3) / Previous EMA3 +``` + +```TypeScript +import { trix } from 'indicatorts'; + +const defaultConfig = { period: 4 }; +const result = trix(values, defaultConfig); + +// Alternatively: +// const result = tripleExponentialAverage(values, defaultConfig); +``` + +## Typical Price + +The [typicalPrice](./typicalPrice.ts) function calculates another approximation of average price for each period and can be used as a filter for moving average systems. + +``` +Typical Price = (High + Low + Closing) / 3 +``` + +```TypeScript +import { typprice } from 'indicatorts'; + +const result = typprice(highs, lows, closings); + +// Alternatively: +// const result = typicalPrice(highs, lows, closings); +``` + +## Volume Weighted Moving Average (VWMA) + +The [vwma](./volumeWeightedMovingAverage.ts) function calculates the Volume Weighted Moving Average (VWMA) averaging the price data with an emphasis on volume, meaning areas with higher volume will have a greater weight. + +``` +VWMA = Sum(Price * Volume) / Sum(Volume) for a given Period. +``` + +```TypeScript +import { vwma } from 'indicatorts'; + +const defaultConfig = { period: 20 }; +const result = vwma(closings, volumes, defaultConfig); + +// Alternatively: +// const result = volumeWeightedMovingAverage(closings, volumes, defaultConfig); +``` + +## Vortex Indicator + +The [vortex](./vortex.ts) function provides two oscillators that capture positive and negative trend movement. A bullish signal triggers when the positive trend indicator crosses above the negative trend indicator or a key level. A bearish signal triggers when the negative trend indicator crosses above the positive trend indicator or a key level. + +``` ++VM = Abs(Current High - Prior Low) +-VM = Abs(Current Low - Prior High) + ++VM14 = 14-Period Sum of +VM +-VM14 = 14-Period Sum of -VM + +TR = Max((High[i]-Low[i]), Abs(High[i]-Closing[i-1]), Abs(Low[i]-Closing[i-1])) +TR14 = 14-Period Sum of TR + ++VI14 = +VM14 / TR14 +-VI14 = -VM14 / TR14 +``` + +```TypeScript +import { vortex } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const { plus, minus } = vortex(highs, lows, closings, defaultConfig); +``` + +Based on [Vortex Indicator](https://school.stockcharts.com/doku.php?id=technical_indicators:vortex_indicator) + +## Disclaimer + +The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. + +## License + +Copyright (c) 2022 Onur Cinar. All Rights Reserved. + +The source code is provided under MIT License. diff --git a/src/indicator/trend/chandeForecastOscillator.ts b/src/indicator/trend/chandeForecastOscillator.ts index eacc190..dbbb820 100644 --- a/src/indicator/trend/chandeForecastOscillator.ts +++ b/src/indicator/trend/chandeForecastOscillator.ts @@ -50,6 +50,20 @@ export function cfo(closings: number[]): number[] { // Export full name export { cfo as chandeForecastOscillator }; +/** + * Optional configuration of moving Chande forecast oscillator parameters. + */ +export interface MCFOConfig { + period?: number; +} + +/** + * The default configuration of moving Chande forecast oscillator. + */ +export const MCFODefaultConfig: Required = { + period: 4, +}; + /** * Moving Chande Forecast Oscillator calculates based on * the given period. @@ -67,11 +81,11 @@ export { cfo as chandeForecastOscillator }; * @param config configuration. * @return moving cfo. */ -export function mcfo(closings: number[], config: CFOConfig = {}): number[] { - const { period } = { ...CFODefaultConfig, ...config }; - const x = generateNumbers(0, closings.length, 1); - const r = movingLinearRegressionUsingLeastSquare(period, x, closings); - const result = multiplyBy(100, divide(subtract(closings, r), closings)); +export function mcfo(closings: number[], config: MCFOConfig = {}): number[] { + const { period } = { ...MCFODefaultConfig, ...config }; + const xVal = generateNumbers(0, closings.length, 1); + const rVal = movingLinearRegressionUsingLeastSquare(period, xVal, closings); + const result = multiplyBy(100, divide(subtract(closings, rVal), closings)); return result; } diff --git a/src/indicator/trend/index.md b/src/indicator/trend/index.md deleted file mode 100644 index 539a780..0000000 --- a/src/indicator/trend/index.md +++ /dev/null @@ -1,429 +0,0 @@ -### Trend Indicators - -Trend indicators measure the direction and strength of a trend. - -- [Absolute Price Oscillator (APO)](#absolute-price-oscillator-apo) -- [Aroon Indicator](#aroon-indicator) -- [Balance of Power (BOP)](trend_indicators.md#balance-of-power-bop) -- [Chande Forecast Oscillator (CFO)](#chande-forecast-oscillator-cfo) -- [Community Channel Index (CMI)](#community-channel-index-cmi) -- [Double Exponential Moving Average (DEMA)](#double-exponential-moving-average-dema) -- [Exponential Moving Average (EMA)](#exponential-moving-average-ema) -- [Mass Index (MI)](#mass-index-mi) -- [Moving Average Convergence Divergence (MACD)](#moving-average-convergence-divergence-macd) -- [Moving Max](#moving-max) -- [Moving Min](#moving-min) -- [Moving Sum](#moving-sum) -- [Parabolic SAR](#parabolic-sar) -- [Qstick](trend_indicator.md#qstick) -- [Random Index (KDJ)](#random-index-kdj) -- [Rolling Moving Average (RMA)](#rolling-moving-average-rma) -- [Simple Moving Average (SMA)](#simple-moving-average-sma) -- [Since Change](#since-change) -- [Triple Exponential Moving Average (TEMA)](#triple-exponential-moving-average-tema) -- [Triangular Moving Average (TRIMA)](#triangular-moving-average-trima) -- [Triple Exponential Average (TRIX)](#triple-exponential-average-trix) -- [Typical Price](#typical-price) -- [Volume Weighted Moving Average (VWMA)](#volume-weighted-moving-average-vwma) -- [Vortex Indicator](#vortex-indicator) - -#### Absolute Price Oscillator (APO) - -The [absolutePriceOscillator](./absolutePriceOscillator.ts) function calculates a technical indicator that is used to follow trends. APO crossing above zero indicates bullish, while crossing below zero indicates bearish. Positive value is upward trend, while negative value is downward trend. Passing a configuration object with the period is also possible, but is optional. The default fast period is `14` and the default slow period is `30`. - -``` -Fast = Ema(fastPeriod, values) -Slow = Ema(slowPeriod, values) -APO = Fast - Slow -``` - -```TypeScript -import {absolutePriceOscillator} from 'indicatorts'; - -const result = absolutePriceOscillator(values, { fast: 14, slow: 30 }); -``` - -#### Aroon Indicator - -The [Aroon](./aroon.ts) function calculates a technical indicator that is used to identify trend changes in the price of a stock, as well as the strength of that trend. It consists of two lines, Aroon Up, and Aroon Down. The Aroon Up line measures measures the strength of the uptrend, and the Aroon Down measures the strength of the downtrend. When Aroon Up is above Aroon Down, it indicates bullish price, and when Aroon Down is above Aroon Up, it indicates bearish price. Passing a configuration object with the period is also possible, but is optional. The default period is `25`. - -``` -Aroon Up = ((25 - Period Since Last 25 Period High) / 25) * 100 -Aroon Down = ((25 - Period Since Last 25 Period Low) / 25) * 100 -``` - -```TypeScript -import {aroon} from 'indicatorts'; - -const result = aroon(highs, lows, { period: 25 }); -``` - -#### Balance of Power (BOP) - -The [BalanceOfPower](./balanceOfPower.ts) function calculates the strength of buying and selling pressure. Positive value indicates an upward trend, and negative value indicates a downward trend. Zero indicates a balance between the two. - -``` -BOP = (Closing - Opening) / (High - Low) -``` - -```Typescript -import {balanceOfPower} from 'indicatorts'; - -const bop = balanceOfPower(openings, highs, lows, closings); -``` - -#### Chande Forecast Oscillator (CFO) - -The [chandeForecastOscillator](./chandeForecastOscillator.ts) developed by Tushar Chande The Forecast Oscillator plots the percentage difference between the closing price and the n-period linear regression forecasted price. The oscillator is above zero when the forecast price is greater than the closing price and less than zero if it is below. - -``` -R = Linreg(Closing) -CFO = ((Closing - R) / Closing) * 100 -``` - -Based on [Chande Forecast Oscillator Formula, Strategy](https://www.stockmaniacs.net/chande-forecast-oscillator/), [Forecast Oscillator -](https://www.fmlabs.com/reference/default.htm?url=ForecastOscillator.htm), and [Least Squares Regression](https://www.mathsisfun.com/data/least-squares-regression.html). - -```TypeScript -import {chandeForecastOscillator} from 'indicatorts'; - -const cfo = chandeForecastOscillator(closings); -``` - -There is also an oscillator for calculating the moving chande forecast oscillator. Passing a configuration object with the period is also possible, but is optional. The default period is `4`. - -```TypeScript -import {movingChandeForecastOscillator} from 'indicatorts'; - -const cfo = movingChandeForecastOscillator(closings, { period: 4 }); -``` - -#### Community Channel Index (CMI) - -The [communityChannelIndex](./communityChannelIndex.ts) is a momentum-based oscillator used to help determine when an investment vehicle is reaching a condition of being overbought or oversold. Passing a configuration object with the period is also possible, but is optional. The default period is `20`. - -``` -Moving Average = Sma(Period, Typical Price) -Mean Deviation = Sma(Period, Abs(Typical Price - Moving Average)) -CMI = (Typical Price - Moving Average) / (0.015 * Mean Deviation) -``` - -```TypeScript -import {communityChannelIndex} from 'indicatorts'; -const result = communityChannelIndex(highs, lows, closings, { period: 20 }); -``` - -#### Double Exponential Moving Average (DEMA) - -The [dema](./dema.ts) function calculates the Double Exponential Moving Average (DEMA) for a given period. - -The double exponential moving average (DEMA) is a technical indicator introduced by Patrick Mulloy. The purpose is to reduce the amount of noise present in price charts used by technical traders. The DEMA uses two exponential moving averages (EMAs) to eliminate lag. It helps confirm uptrends when the price is above the average, and helps confirm downtrends when the price is below the average. When the price crosses the average that may signal a trend change. Passing a configuration object with the period is also possible, but is optional. The default period is `12`. - -``` -DEMA = (2 * EMA(values)) - EMA(EMA(values)) -``` - -```TypeScript -import {dema} from 'indicatorts'; - -const result = dema(values, { period: 12 }); -``` - -Based on [Double Exponential Moving Average (DEMA)](https://www.investopedia.com/terms/d/double-exponential-moving-average.asp). - -#### Exponential Moving Average (EMA) - -The [ema](./ema.ts) function calculates the exponential moving average for a given period. Passing a configuration object with the period is also possible, but is optional. The default period is `12`. - -```TypeScript -import {ema} from 'indicatorts'; - -const result = ema(values, { period: 12 }); -``` - -#### Mass Index (MI) - -The [massIndex](./massIndex.ts) uses the high-low range to identify trend reversals based on range expansions. - -``` -Singe EMA = EMA(9, Highs - Lows) -Double EMA = EMA(9, Single EMA) -Ratio = Single EMA / Double EMA -MI = Sum(25, Ratio) -``` - -```TypeScript -import {massIndex} from 'indicatorts'; - -const result = massIndex(highs, lows); -``` - -#### Moving Average Convergence Divergence (MACD) - -The [macd](./macd.ts) function calculates a trend-following momentum indicator that shows the relationship between two moving averages of price. - -``` -MACD = 12-Period EMA - 26-Period EMA. -Signal = 9-Period EMA of MACD. -``` - -```TypeScript -import {macd} from 'indicatorts'; - -const result = macd(closings); -``` - -#### Moving Max - -The [mmax](./mmax.ts) function gives the maximum value within the given moving period. It can be used to get the moving maximum closing price and other values. Passing a configuration object with the period is also possible, but is optional. The default period is `4`. - -```TypeScript -import {mmax} from 'indicatorts'; - -const result = mmax(values, { period: 4 }); -``` - -#### Moving Min - -The [mmin](./mmin.ts) function gives the minimum value within the given moving period. It can be used to get the moving minimum closing price and other values. Passing a configuration object with the period is also possible, but is optional. The default period is `4`. - -```TypeScript -import {mmin} from 'indicatorts'; - -const result = mmin(values, { period: 4}); -``` - -#### Moving Sum - -The [msum](./msum.ts) function gives the sum value within the given moving period. - -```TypeScript -import {msum} from 'indicatorts'; - -const result = msum(period, values); -``` - -#### Parabolic SAR - -The [parabolicSar](./parabolicSar.ts) function calculates an identifier for the trend and the trailing stop. - -``` -PSAR = PSAR[i - 1] - ((PSAR[i - 1] - EP) * AF) -``` - -If the trend is Falling: - -- PSAR is the maximum of PSAR or the previous two high values. -- If the current high is greather than or equals to PSAR, use EP. - -If the trend is Rising: - -- PSAR is the minimum of PSAR or the previous two low values. -- If the current low is less than or equials to PSAR, use EP. - -If PSAR is greather than the closing, trend is falling, and the EP is set to the minimum of EP or the low. - -If PSAR is lower than or equals to the closing, trend is rising, and the EP is set to the maximum of EP or the high. - -If the trend is the same, and AF is less than 0.20, increment it by 0.02. If the trend is not the same, set AF to 0.02. - -Based on video [How to Calculate the PSAR Using Excel - Revised Version](https://www.youtube.com/watch?v=MuEpGBAH7pw&t=0s). - -```TypeScript -import {parabolicSar} from 'indicatorts'; - -const result = parabolicSar(highs, lows, closings); -``` - -#### Qstick - -The [qstick](./qstick.ts) function calculates the ratio of recent up and down bars. - -``` -QS = Sma(Closing - Opening) -``` - -```TypeScript -import {qstick} from 'indicatorts'; - -const result = qstick(period, openings, closings); -``` - -#### Random Index (KDJ) - -The [kdj](./kdj.ts) function calculates the KDJ indicator, also known as the Random Index. KDJ is calculated similar to the Stochastic Oscillator with the difference of having the J line. It is used to analyze the trend and entry points. - -The K and D lines show if the asset is overbought when they crosses above 80%, and oversold when they crosses below 20%. The J line represents the divergence. - -Passing a configuration object with the r, k, and d period is also possible, but is optional. The default r period is `9`, the default k period is `3` and the default d period is `3`. - -``` -RSV = ((Closing - Min(Low, rPeriod)) / (Max(High, rPeriod) - Min(Low, rPeriod))) * 100 -K = Sma(RSV, kPeriod) -D = Sma(K, dPeriod) -J = (3 * K) - (2 * D) -``` - -```TypeScript -import {kdj} from 'indicatorts'; - -const result = kdj(highs, lows, closings, { rPeriod: 9, kPeriod: 3, dPeriod: 3 }); -``` - -#### Rolling Moving Average (RMA) - -The [rma](./rma.ts) function calculates the rolling moving average for a given period. - -``` -R[0] to R[p-1] is SMA(values) -R[p] and after is R[i] = ((R[i-1]*(p-1)) + v[i]) / p -``` - -```TypeScript -import {rma} from 'indicatorts'; - -const result = rma(period, values); -``` - -#### Simple Moving Average (SMA) - -The [sma](./sma.ts) function calculates the simple moving average for a given period. - -```TypeScript -import {sma} from 'indicatorts'; - -const result = sma(period, values); -``` - -#### Since Change - -The [since](./since.ts) function provides the number values since the last change. - -```TypeScript -import {since} from 'indicatorts'; - -const result = since(values); -``` - -#### Triple Exponential Moving Average (TEMA) - -The [tema](./tema.ts) function calculates the Triple Exponential Moving Average (TEMA) for a given period. - -The triple exponential moving average (TEMA) was designed to smooth value fluctuations, thereby making it easier to identify trends without the lag associated with traditional moving averages. It does this by taking multiple exponential moving averages (EMA) of the original EMA and subtracting out some of the lag. - -``` -TEMA = (3 * EMA1) - (3 * EMA2) + EMA3 -EMA1 = EMA(values) -EMA2 = EMA(EMA1) -EMA3 = EMA(EMA2) -``` - -```TypeScript -import {tema} from 'indicatorts'; - -const result = tema(period, values); -``` - -Based on [Triple Exponential Moving Average (TEMA)](https://www.investopedia.com/terms/t/triple-exponential-moving-average.asp). - -#### Triangular Moving Average (TRIMA) - -The [trima](./trima.ts) function calculates the Triangular Moving Average (TRIMA) for a given period. - -The Triangular Moving Average (TRIMA) is a weighted moving average putting more weight to the middle values. - -``` -If period is even: - TRIMA = SMA(period / 2, SMA((period / 2) + 1, values)) -If period is odd: - TRIMA = SMA((period + 1) / 2, SMA((period + 1) / 2, values)) -``` - -```TypeScript -import {trima} from 'indicatorts'; - -const result = trima(period, values); -``` - -Based on [Triangular Moving Average](https://tulipindicators.org/trima). - -#### Triple Exponential Average (TRIX) - -The [trix](./trix.ts) indicator is an oscillator used to identify oversold and overbought markets, and it can also be used as a momentum indicator. Like many oscillators, TRIX oscillates around a zero line. - -``` -EMA1 = EMA(period, values) -EMA2 = EMA(period, EMA1) -EMA3 = EMA(period, EMA2) -TRIX = (EMA3 - Previous EMA3) / Previous EMA3 -``` - -```TypeScript -import {trix} from 'indicatorts'; - -const result = trix(period, values); -``` - -#### Typical Price - -The [typicalPrice](./typicalPrice.ts) function calculates another approximation of average price for each period and can be used as a filter for moving average systems. - -``` -Typical Price = (High + Low + Closing) / 3 -``` - -```TypeScript -import {typicalPrice} from 'indicatorts'; - -const result = typicalPrice(highs, lows, closings); -``` - -#### Volume Weighted Moving Average (VWMA) - -The [vwma](./vwma.ts) function calculates the Volume Weighted Moving Average (VWMA) averaging the price data with an emphasis on volume, meaning areas with higher volume will have a greater weight. - -``` -VWMA = Sum(Price * Volume) / Sum(Volume) for a given Period. -``` - -```TypeScript -import {vwma} from 'indicatorts'; - -const result = vwma(period, closings, volumes); -``` - -#### Vortex Indicator - -The [vortex](./vortex.ts) function provides two oscillators that capture positive and negative trend movement. A bullish signal triggers when the positive trend indicator crosses above the negative trend indicator or a key level. A bearish signal triggers when the negative trend indicator crosses above the positive trend indicator or a key level. - -``` -+VM = Abs(Current High - Prior Low) --VM = Abs(Current Low - Prior High) - -+VM14 = 14-Period Sum of +VM --VM14 = 14-Period Sum of -VM - -TR = Max((High[i]-Low[i]), Abs(High[i]-Closing[i-1]), Abs(Low[i]-Closing[i-1])) -TR14 = 14-Period Sum of TR - -+VI14 = +VM14 / TR14 --VI14 = -VM14 / TR14 -``` - -Based on [Vortex Indicator](https://school.stockcharts.com/doku.php?id=technical_indicators:vortex_indicator) - -```TypeScript -import {vortex} from 'indicatorts'; - -const result = vortex(highs, lows, closings); -``` - -## Disclaimer - -The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. - -## License - -Copyright (c) 2022 Onur Cinar. All Rights Reserved. - -The source code is provided under MIT License. diff --git a/src/indicator/trend/index.ts b/src/indicator/trend/index.ts index 2695ea0..1abb029 100644 --- a/src/indicator/trend/index.ts +++ b/src/indicator/trend/index.ts @@ -8,7 +8,6 @@ export * from './chandeForecastOscillator'; export * from './communityChannelIndex'; export * from './doubleExponentialMovingAverage'; export * from './exponentialMovingAverage'; -export * from './kdj'; export * from './massIndex'; export * from './movingAverageConvergenceDivergence'; export * from './movingMax'; @@ -16,6 +15,7 @@ export * from './movingMin'; export * from './movingSum'; export * from './parabolicSar'; export * from './qstick'; +export * from './randomIndex'; export * from './rollingMovingAverage'; export * from './simpleMovingAverage'; export * from './since'; diff --git a/src/indicator/trend/movingAverageConvergenceDivergence.test.ts b/src/indicator/trend/movingAverageConvergenceDivergence.test.ts index 998cfe1..ebfcc6d 100644 --- a/src/indicator/trend/movingAverageConvergenceDivergence.test.ts +++ b/src/indicator/trend/movingAverageConvergenceDivergence.test.ts @@ -17,8 +17,8 @@ describe('Moving Average Convergence Divergence (MACD)', () => { ]; const actual = macd(closings, { fast: 14, slow: 28, signal: 7 }); - deepStrictEqual(roundDigitsAll(2, actual.macd), expectedMACD); - deepStrictEqual(roundDigitsAll(2, actual.signal), expectedSignal); + deepStrictEqual(roundDigitsAll(2, actual.macdLine), expectedMACD); + deepStrictEqual(roundDigitsAll(2, actual.signalLine), expectedSignal); }); it('should be able to compute without a config', () => { @@ -30,7 +30,7 @@ describe('Moving Average Convergence Divergence (MACD)', () => { ]; const actual = macd(closings); - deepStrictEqual(roundDigitsAll(2, actual.macd), expectedMACD); - deepStrictEqual(roundDigitsAll(2, actual.signal), expectedSignal); + deepStrictEqual(roundDigitsAll(2, actual.macdLine), expectedMACD); + deepStrictEqual(roundDigitsAll(2, actual.signalLine), expectedSignal); }); }); diff --git a/src/indicator/trend/movingAverageConvergenceDivergence.ts b/src/indicator/trend/movingAverageConvergenceDivergence.ts index a861c3c..1eff707 100644 --- a/src/indicator/trend/movingAverageConvergenceDivergence.ts +++ b/src/indicator/trend/movingAverageConvergenceDivergence.ts @@ -5,8 +5,8 @@ import { subtract } from '../../helper/numArray'; import { ema } from './exponentialMovingAverage'; export interface MACDResult { - macd: number[]; - signal: number[]; + macdLine: number[]; + signalLine: number[]; } /** @@ -49,8 +49,8 @@ export function macd(closings: number[], config: MACDConfig = {}): MACDResult { const signalLine = ema(macdLine, { period: signal }); return { - macd: macdLine, - signal: signalLine, + macdLine, + signalLine, }; } diff --git a/src/indicator/trend/parabolicSar.test.ts b/src/indicator/trend/parabolicSar.test.ts index 8d3efe9..011167f 100644 --- a/src/indicator/trend/parabolicSar.test.ts +++ b/src/indicator/trend/parabolicSar.test.ts @@ -43,7 +43,7 @@ describe('Parabolic SAR (SAR)', () => { step: 0.01, max: 0.3, }); - deepStrictEqual(roundDigitsAll(2, actual.psar), expectedPsar); + deepStrictEqual(roundDigitsAll(2, actual.psarResult), expectedPsar); deepStrictEqual(actual.trends, expectedTrends); }); @@ -65,7 +65,7 @@ describe('Parabolic SAR (SAR)', () => { ]; const actual = psar(highs, lows, closings); - deepStrictEqual(roundDigitsAll(2, actual.psar), expectedPsar); + deepStrictEqual(roundDigitsAll(2, actual.psarResult), expectedPsar); deepStrictEqual(actual.trends, expectedTrends); }); }); diff --git a/src/indicator/trend/parabolicSar.ts b/src/indicator/trend/parabolicSar.ts index a95e475..c61d3d2 100644 --- a/src/indicator/trend/parabolicSar.ts +++ b/src/indicator/trend/parabolicSar.ts @@ -9,7 +9,7 @@ import { Trend } from '../types'; */ export interface PSARResult { trends: Trend[]; - psar: number[]; + psarResult: number[]; } /** @@ -72,40 +72,40 @@ export function psar( ...config, }; const trends = new Array(highs.length); - const psar = new Array(highs.length); + const psarResult = new Array(highs.length); trends[0] = Trend.FALLING; - psar[0] = highs[0]; + psarResult[0] = highs[0]; let af = step; let ep = lows[0]; - for (let i = 1; i < psar.length; i++) { - psar[i] = psar[i - 1] - (psar[i - 1] - ep) * af; + for (let i = 1; i < psarResult.length; i++) { + psarResult[i] = psarResult[i - 1] - (psarResult[i - 1] - ep) * af; if (trends[i - 1] === Trend.FALLING) { - psar[i] = Math.max(psar[i], highs[i - 1]); + psarResult[i] = Math.max(psarResult[i], highs[i - 1]); if (i > 1) { - psar[i] = Math.max(psar[i], highs[i - 2]); + psarResult[i] = Math.max(psarResult[i], highs[i - 2]); } - if (highs[i] >= psar[i]) { - psar[i] = ep; + if (highs[i] >= psarResult[i]) { + psarResult[i] = ep; } } else { - psar[i] = Math.min(psar[i], lows[i - 1]); + psarResult[i] = Math.min(psarResult[i], lows[i - 1]); if (i > 1) { - psar[i] = Math.min(psar[i], lows[i - 2]); + psarResult[i] = Math.min(psarResult[i], lows[i - 2]); } - if (lows[i] <= psar[i]) { - psar[i] = ep; + if (lows[i] <= psarResult[i]) { + psarResult[i] = ep; } } const prevEp = ep; - if (psar[i] > closings[i]) { + if (psarResult[i] > closings[i]) { trends[i] = Trend.FALLING; ep = Math.min(ep, lows[i]); } else { @@ -122,7 +122,7 @@ export function psar( return { trends, - psar, + psarResult, }; } diff --git a/src/indicator/trend/kdj.test.ts b/src/indicator/trend/randomIndex.test.ts similarity index 95% rename from src/indicator/trend/kdj.test.ts rename to src/indicator/trend/randomIndex.test.ts index 2be3415..a97df5e 100644 --- a/src/indicator/trend/kdj.test.ts +++ b/src/indicator/trend/randomIndex.test.ts @@ -3,9 +3,9 @@ import { deepStrictEqual } from 'assert'; import { roundDigitsAll } from '../../helper/numArray'; -import { kdj } from './kdj'; +import { kdj } from './randomIndex'; -describe('KDJ', () => { +describe('Random Index (KDJ)', () => { const lows = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const highs = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; const closings = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]; diff --git a/src/indicator/trend/kdj.ts b/src/indicator/trend/randomIndex.ts similarity index 97% rename from src/indicator/trend/kdj.ts rename to src/indicator/trend/randomIndex.ts index 6c0edaf..195a533 100644 --- a/src/indicator/trend/kdj.ts +++ b/src/indicator/trend/randomIndex.ts @@ -80,3 +80,6 @@ export function kdj( j: jValue, }; } + +// Export full name +export { kdj as randomIndex }; diff --git a/src/indicator/volatility/README.md b/src/indicator/volatility/README.md new file mode 100644 index 0000000..637e025 --- /dev/null +++ b/src/indicator/volatility/README.md @@ -0,0 +1,242 @@ +# Volatility Indicators + +Volatility indicators measure the rate of movement regardless of its direction. + +- [Volatility Indicators](#volatility-indicators) + - [Acceleration Bands (AB)](#acceleration-bands-ab) + - [Average True Range (ATR)](#average-true-range-atr) + - [Bollinger Bands (BB)](#bollinger-bands-bb) + - [Bollinger Band Width (BBW)](#bollinger-band-width-bbw) + - [Chandelier Exit (CE)](#chandelier-exit-ce) + - [Donchian Channel (DC)](#donchian-channel-dc) + - [Keltner Channel (KC)](#keltner-channel-kc) + - [Moving Standard Deviation (MSTD)](#moving-standard-deviation-mstd) + - [Projection Oscillator (PO)](#projection-oscillator-po) + - [True Range (TR)](#true-range-tr) + - [Ulcer Index (UI)](#ulcer-index-ui) + - [Disclaimer](#disclaimer) + - [License](#license) + +**NOTE:** All configuration objects for all indicators are optional. If no configuration object is passed, the default configuration will be used. Likewise, you may also partially pass a configuration object, and the default values will be used for the missing properties. + +## Acceleration Bands (AB) + +The [accelerationBands](./accelerationBands.ts) plots upper and lower envelope bands around a simple moving average. + +``` +Upper Band = SMA(High * (1 + 4 * (High - Low) / (High + Low))) +Middle Band = SMA(Closing) +Lower Band = SMA(Low * (1 + 4 * (High - Low) / (High + Low))) +``` + +```TypeScript +import { ab } from 'indicatorts'; + +const defaultConfig = { period: 20, multiplier: 4 }; +const { upper, middle, lower } = ab(highs, lows, closings, defaultConfig); + +// Alternatively: +// const { upper, middle, lower } = accelerationBands(highs, lows, closings, defaultConfig); +``` + +## Average True Range (ATR) + +The [atr](./averageTrueRange.ts) function calculates a technical analysis indicator that measures market volatility by decomposing the entire range of stock prices for that period. + +``` +TR = Max((High - Low), (High - Closing), (Closing - Low)) +ATR = 14-Period SMA TR +``` + +```TypeScript +import { atr } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const { trLine, atrLine } = atr(highs, lows, closings, defaultConfig); + +// Alternatively: +// const { trLine, atrLine } = averageTrueRange(highs, lows, closings, defaultConfig); +``` + +## Bollinger Bands (BB) + +The [bollingerBands](./bollingerBands.ts) function calculates the bollinger bands, middle band, upper band, lower band, provides identification of when a stock is oversold or overbought. + +``` +Middle Band = 20-Period SMA. +Upper Band = 20-Period SMA + 2 (20-Period Std) +Lower Band = 20-Period SMA - 2 (20-Period Std) +``` + +```TypeScript +import { bb } from 'indicatorts'; + +const defaultConfig = { period: 20 }; +const { upper, middle, lower } = bb(closings, defaultConfig); + +// Alternatively: +// const { upper, middle, lower } = bollingerBands(closings, defaultConfig); +``` + +## Bollinger Band Width (BBW) + +The [bollingerBandsWidth](./bollingerBandsWidth.ts) function measures the percentage difference between the upper band and the lower band. It decreases as Bollinger Bands narrows and increases as Bollinger Bands widens. + +During a period of rising price volatility the band width widens, and during a period of low market volatility band width contracts. + +``` +Band Width = (Upper Band - Lower Band) / Middle Band +``` + +```TypeScript +import { bb, bbw } from 'indicatorts'; + +const bbResult = bb(closings); + +const defaultConfig = { period: 90 }; +const { width, widthEma } = bbw(bbResult, defaultConfig); + +// Alternatively: +// const { width, widthEma } = bollingerBandsWidth(bbResult, defaultConfig); +``` + +## Chandelier Exit (CE) + +The [chandelierExit](./chandelierExit.ts) function sets a trailing stop-loss based on the Average True Value (ATR). + +``` +Chandelier Exit Long = 22-Period SMA High - ATR(22) * 3 +Chandelier Exit Short = 22-Period SMA Low + ATR(22) * 3 +``` + +```TypeScript +import { ce } from 'indicatorts'; + +const defaultConfig = { period: 22 }; +const { long, short } = ce(highs, lows, closings, defaultConfig); + +// Alternatively: +// const { long, short } = chandelierExit(highs, lows, closings, defaultConfig); +``` + +## Donchian Channel (DC) + +The [donchianChannel](./donchianChannel.ts) calculates three lines generated by moving average calculations that comprise an indicator formed by upper and lower bands around a midrange or median band. The upper band marks the highest price of an asset while the lower band marks the lowest price of an asset, and the area between the upper and lower bands represents the Donchian Channel. + +``` +Upper Channel = Mmax(closings, { period }) +Lower Channel = Mmin(closings, { period }) +Middle Channel = (Upper Channel + Lower Channel) / 2 +``` + +```TypeScript +import { dc } from 'indicatorts'; + +const defaultConfig = { period: 4 }; +const { upper, middle, lower } = dc(closings, defaultConfig); + +// Alternatively: +// const { upper, middle, lower } = donchianChannel(closings, defaultConfig); +``` + +## Keltner Channel (KC) + +The [keltnerChannel](./keltnerChannel.ts) provides volatility-based bands that are placed on either side of an asset's price and can aid in determining the direction of a trend. + +``` +Middle Line = EMA(period, closings) +Upper Band = EMA(period, closings) + 2 * ATR(period, highs, lows, closings) +Lower Band = EMA(period, closings) - 2 * ATR(period, highs, lows, closings) +``` + +```TypeScript +import { kc } from 'indicatorts'; + +const defaultConfig = { period: 20 }; +const { upper, middle, lower } = kc(highs, lows, closings, defaultConfig); + +// Alternatively: +// const { upper, middle, lower } = keltnerChannel(highs, lows, closings, defaultConfig); +``` + +## Moving Standard Deviation (MSTD) + +The [mstd](./movingStandardDeviation.ts) function calculates the moving standard deviation for a given period. + +```TypeScript +import { mstd } from 'indicatorts'; + +const defaultConfig = { period: 4 }; +const result = mstd(values, defaultConfig); + +// Alternatively: +// const result = movingStandardDeviation(values, defaultConfig); +``` + +## Projection Oscillator (PO) + +The [projectionOscillator](./projectionOscillator.ts) calculates the Projection Oscillator (PO). The PO uses the linear regression slope, along with highs and lows. + +Period defines the moving window to calculates the PO, and the smooth period defines the moving windows to take EMA of PO. + +``` +PL = Min(period, (high + MLS(period, x, high))) +PU = Max(period, (low + MLS(period, x, low))) +PO = 100 * (Closing - PL) / (PU - PL) +SPO = EMA(smooth, PO) +``` + +```TypeScript +import { po } from 'indicatorts'; + +const defaultConfig = { period: 14, smooth: 3 }; +const { poResult, spoResult } = po(highs, lows, closings, defaultConfig); + +// Alternatively: +// const { poResult, spoResult } = projectionOscillator(highs, lows, closings, defaultConfig); +``` + +## True Range (TR) + +The [trueRange](./trueRange.ts) function calculates the True Range (TR) for a given period. + +``` +TR = Max((High - Low), Abs(High - Closing[-1]), Abs(Low - Closing[-1])) +``` + +```TypeScript +import { tr } from 'indicatorts'; + +const result = tr(highs, lows, closings); +``` + +## Ulcer Index (UI) + +The [ulcerIndex](./ulcerIndex.ts) measures downside risk. The index increases in value as the price moves farther away from a recent high and falls as the price rises to new highs. + +``` +High Closings = Max(period, Closings) +Percentage Drawdown = 100 * ((Closings - High Closings) / High Closings) +Squared Average = Sma(period, Percent Drawdown * Percent Drawdown) +Ulcer Index = Sqrt(Squared Average) +``` + +```TypeScript +import { ui } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const result = ulcerIndex(closings, defaultConfig); + +// Alternatively: +// const result = ulcerIndex(closings, defaultConfig); +``` + +## Disclaimer + +The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. + +## License + +Copyright (c) 2022 Onur Cinar. All Rights Reserved. + +The source code is provided under MIT License. diff --git a/src/indicator/volatility/accelerationBands.ts b/src/indicator/volatility/accelerationBands.ts index 950642d..edfbc53 100644 --- a/src/indicator/volatility/accelerationBands.ts +++ b/src/indicator/volatility/accelerationBands.ts @@ -26,6 +26,7 @@ export interface ABResult { */ export interface ABConfig { period?: number; + multiplier?: number; } /** @@ -33,6 +34,7 @@ export interface ABConfig { */ export const ABDefaultConfig: Required = { period: 20, + multiplier: 4, }; /** @@ -57,14 +59,14 @@ export function ab( ): ABResult { checkSameLength(highs, lows, closings); - const { period } = { ...ABDefaultConfig, ...config }; + const { period, multiplier } = { ...ABDefaultConfig, ...config }; const k = divide(subtract(highs, lows), add(highs, lows)); - const upper = sma(multiply(highs, addBy(1, multiplyBy(4, k))), { + const upper = sma(multiply(highs, addBy(1, multiplyBy(multiplier, k))), { period, }); const middle = sma(closings, { period }); - const lower = sma(multiply(lows, addBy(1, multiplyBy(-4, k))), { + const lower = sma(multiply(lows, addBy(1, multiplyBy(-1 * multiplier, k))), { period, }); diff --git a/src/indicator/volatility/averageTrueRange.test.ts b/src/indicator/volatility/averageTrueRange.test.ts index 6a70de3..21c3767 100644 --- a/src/indicator/volatility/averageTrueRange.test.ts +++ b/src/indicator/volatility/averageTrueRange.test.ts @@ -14,8 +14,8 @@ describe('Average True Range (ATR)', () => { const expectedAtr = [4, 3, 3, 4, 3.6]; const actual = atr(highs, lows, closings, { period: 9 }); - expect(roundDigitsAll(2, actual.tr)).toStrictEqual(expectedTr); - expect(roundDigitsAll(2, actual.atr)).toStrictEqual(expectedAtr); + expect(roundDigitsAll(2, actual.trLine)).toStrictEqual(expectedTr); + expect(roundDigitsAll(2, actual.atrLine)).toStrictEqual(expectedAtr); }); it('should be able to compute without a config', () => { @@ -23,7 +23,7 @@ describe('Average True Range (ATR)', () => { const expectedAtr = [4, 3, 3, 4, 3.6]; const actual = atr(highs, lows, closings); - expect(roundDigitsAll(2, actual.tr)).toStrictEqual(expectedTr); - expect(roundDigitsAll(2, actual.atr)).toStrictEqual(expectedAtr); + expect(roundDigitsAll(2, actual.trLine)).toStrictEqual(expectedTr); + expect(roundDigitsAll(2, actual.atrLine)).toStrictEqual(expectedAtr); }); }); diff --git a/src/indicator/volatility/averageTrueRange.ts b/src/indicator/volatility/averageTrueRange.ts index f4a2271..a9cb901 100644 --- a/src/indicator/volatility/averageTrueRange.ts +++ b/src/indicator/volatility/averageTrueRange.ts @@ -8,8 +8,8 @@ import { sma } from '../trend/simpleMovingAverage'; * Average true range result. */ export interface ATRResult { - tr: number[]; - atr: number[]; + trLine: number[]; + atrLine: number[]; } /** @@ -51,8 +51,8 @@ export function atr( const atrLine = sma(trLine, { period }); return { - tr: trLine, - atr: atrLine, + trLine, + atrLine, }; } diff --git a/src/indicator/volatility/chandelierExit.ts b/src/indicator/volatility/chandelierExit.ts index fd067bb..f882e8a 100644 --- a/src/indicator/volatility/chandelierExit.ts +++ b/src/indicator/volatility/chandelierExit.ts @@ -49,7 +49,7 @@ export function ce( ): CEResult { const { period } = { ...CEDefaultConfig, ...config }; const atrResult = atr(highs, lows, closings, { period }); - const atrLine3 = multiplyBy(3, atrResult.atr); + const atrLine3 = multiplyBy(3, atrResult.atrLine); const highestHigh = mmax(highs, { period }); const lowestLow = mmin(lows, { period }); diff --git a/src/indicator/volatility/index.md b/src/indicator/volatility/index.md deleted file mode 100644 index 061596d..0000000 --- a/src/indicator/volatility/index.md +++ /dev/null @@ -1,180 +0,0 @@ -### Volatility Indicators - -Volatility indicators measure the rate of movement regardless of its direction. - -- [Acceleration Bands](#acceleration-bands) -- [Average True Range (ATR)](#average-true-range-atr) -- [Bollinger Band Width](#bollinger-band-width) -- [Bollinger Bands](#bollinger-bands) -- [Chandelier Exit](#chandelier-exit) -- [Donchian Channel (DC)](#donchian-channel-dc) -- [Keltner Channel (KC)](#keltner-channel-kc) -- [Moving Standard Deviation (Std)](#moving-standard-deviation-std) -- [Projection Oscillator (PO)](#projection-oscillator-po) -- [Ulcer Index (UI)](#ulcer-index-ui) - -#### Acceleration Bands - -The [accelerationBands](./accelerationBands.ts) plots upper and lower envelope bands around a simple moving average. - -``` -Upper Band = SMA(High * (1 + 4 * (High - Low) / (High + Low))) -Middle Band = SMA(Closing) -Lower Band = SMA(Low * (1 + 4 * (High - Low) / (High + Low))) -``` - -```TypeScript -import {accelerationBands} from 'indicatorts'; - -const result = accelerationBands(highs, lows, closings); -``` - -#### Average True Range (ATR) - -The [atr](./atr.ts) function calculates a technical analysis indicator that measures market volatility by decomposing the entire range of stock prices for that period. - -``` -TR = Max((High - Low), (High - Closing), (Closing - Low)) -ATR = 14-Period SMA TR -``` - -```TypeScript -import {atr} from 'indicatorts'; - -const result = atr(period, highs, lows, closings); -``` - -#### Bollinger Bands - -The [bollingerBands](./bollingerBands.ts) function calculates the bollinger bands, middle band, upper band, lower band, provides identification of when a stock is oversold or overbought. - -``` -Middle Band = 20-Period SMA. -Upper Band = 20-Period SMA + 2 (20-Period Std) -Lower Band = 20-Period SMA - 2 (20-Period Std) -``` - -```TypeScript -import {bollingerBands} from 'indicatorts'; - -const result = bollingerBands(closings); -``` - -#### Bollinger Band Width - -The [bollingerBandsWidth](./bollingerBandsWidth.ts) function measures the percentage difference between the upper band and the lower band. It decreases as Bollinger Bands narrows and increases as Bollinger Bands widens. - -During a period of rising price volatility the band width widens, and during a period of low market volatility band width contracts. - -``` -Band Width = (Upper Band - Lower Band) / Middle Band -``` - -```TypeScript -import {bollingerBandsWidth} from 'indicatorts'; - -const result = bollingerBandsWidth(bollingerBandsResult); -``` - -#### Chandelier Exit - -The [chandelierExit](https://pkg.go.dev/github.com/cinar/indicator#ChandelierExit) function sets a trailing stop-loss based on the Average True Value (ATR). - -``` -Chandelier Exit Long = 22-Period SMA High - ATR(22) * 3 -Chandelier Exit Short = 22-Period SMA Low + ATR(22) * 3 -``` - -```TypeScript -import {chandelierExit} from 'indicatorts'; - -const result = chandelierExit(highs, lows, closings); -``` - -#### Donchian Channel (DC) - -The [donchianChannel](./donchianChannel.ts) calculates three lines generated by moving average calculations that comprise an indicator formed by upper and lower bands around a midrange or median band. The upper band marks the highest price of an asset while the lower band marks the lowest price of an asset, and the area between the upper and lower bands represents the Donchian Channel. - -``` -Upper Channel = Mmax(closings, { period }) -Lower Channel = Mmin(closings, { period }) -Middle Channel = (Upper Channel + Lower Channel) / 2 -``` - -```TypeScript -import {donchianChannel} from 'indicatorts'; - -const result = donchianChannel(period, closings); -``` - -#### Keltner Channel (KC) - -The [keltnerChannel](./keltnerChannel.ts) provides volatility-based bands that are placed on either side of an asset's price and can aid in determining the direction of a trend. - -``` -Middle Line = EMA(period, closings) -Upper Band = EMA(period, closings) + 2 * ATR(period, highs, lows, closings) -Lower Band = EMA(period, closings) - 2 * ATR(period, highs, lows, closings) -``` - -```TypeScript -import {keltnerChannel} from 'indicatorts'; - -const result = keltnerChannel(period, highs, lows, closings); -``` - -#### Moving Standard Deviation (Std) - -The [mstd](./mstd.ts) function calculates the moving standard deviation for a given period. - -```TypeScript -import {mstd} from 'indicatorts'; - -const result = mstd(values, { period }); -``` - -#### Projection Oscillator (PO) - -The [projectionOscillator](./projectionOscillator.ts) calculates the Projection Oscillator (PO). The PO uses the linear regression slope, along with highs and lows. - -Period defines the moving window to calculates the PO, and the smooth period defines the moving windows to take EMA of PO. - -``` -PL = Min(period, (high + MLS(period, x, high))) -PU = Max(period, (low + MLS(period, x, low))) -PO = 100 * (Closing - PL) / (PU - PL) -SPO = EMA(smooth, PO) -``` - -```TypeScript -import {projectionOscillator} from 'indicatorts'; - -const result = projectionOscillator(period, smooth, highs, lows, closings); -``` - -#### Ulcer Index (UI) - -The [ulcerIndex](./ulcerIndex.ts) measures downside risk. The index increases in value as the price moves farther away from a recent high and falls as the price rises to new highs. - -``` -High Closings = Max(period, Closings) -Percentage Drawdown = 100 * ((Closings - High Closings) / High Closings) -Squared Average = Sma(period, Percent Drawdown * Percent Drawdown) -Ulcer Index = Sqrt(Squared Average) -``` - -```TypeScript -import {ulcerIndex} from 'indicatorts'; - -const result = ulcerIndex(period, closings); -``` - -## Disclaimer - -The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. - -## License - -Copyright (c) 2022 Onur Cinar. All Rights Reserved. - -The source code is provided under MIT License. diff --git a/src/indicator/volatility/keltnerChannel.ts b/src/indicator/volatility/keltnerChannel.ts index c2d490f..6a77de0 100644 --- a/src/indicator/volatility/keltnerChannel.ts +++ b/src/indicator/volatility/keltnerChannel.ts @@ -5,17 +5,12 @@ import { add, multiplyBy, subtract } from '../../helper/numArray'; import { ema } from '../trend/exponentialMovingAverage'; import { atr } from './averageTrueRange'; -/** - * Default period for KC. - */ -export const KC_PERIOD = 20; - /** * Keltner channel result object. */ export interface KCResult { - middle: number[]; upper: number[]; + middle: number[]; lower: number[]; } @@ -56,7 +51,7 @@ export function kc( ): KCResult { const { period } = { ...KCDefaultConfig, ...config }; const atrResult = atr(highs, lows, closings, { period }); - const atr2 = multiplyBy(2, atrResult.atr); + const atr2 = multiplyBy(2, atrResult.atrLine); const middle = ema(closings, { period }); const upper = add(middle, atr2); diff --git a/src/indicator/volatility/projectionOscillator.test.ts b/src/indicator/volatility/projectionOscillator.test.ts index 9cf8157..8defea8 100644 --- a/src/indicator/volatility/projectionOscillator.test.ts +++ b/src/indicator/volatility/projectionOscillator.test.ts @@ -14,8 +14,8 @@ describe('Projection Oscillator (PO)', () => { const expectedSPO = [75, 108.33, 44.44, 36.15, 22.72]; const actual = po(highs, lows, closings, { period: 9, smooth: 2 }); - expect(roundDigitsAll(2, actual.po)).toStrictEqual(expectedPO); - expect(roundDigitsAll(2, actual.spo)).toStrictEqual(expectedSPO); + expect(roundDigitsAll(2, actual.poResult)).toStrictEqual(expectedPO); + expect(roundDigitsAll(2, actual.spoResult)).toStrictEqual(expectedSPO); }); it('should be able to compute without a config', () => { @@ -23,7 +23,7 @@ describe('Projection Oscillator (PO)', () => { const expectedSPO = [75, 100, 56.25, 44.13, 30.06]; const actual = po(highs, lows, closings); - expect(roundDigitsAll(2, actual.po)).toStrictEqual(expectedPO); - expect(roundDigitsAll(2, actual.spo)).toStrictEqual(expectedSPO); + expect(roundDigitsAll(2, actual.poResult)).toStrictEqual(expectedPO); + expect(roundDigitsAll(2, actual.spoResult)).toStrictEqual(expectedSPO); }); }); diff --git a/src/indicator/volatility/projectionOscillator.ts b/src/indicator/volatility/projectionOscillator.ts index 37858fe..c2f7ddd 100644 --- a/src/indicator/volatility/projectionOscillator.ts +++ b/src/indicator/volatility/projectionOscillator.ts @@ -18,8 +18,8 @@ import { mmin } from '../trend/movingMin'; * Projection oscillator result object. */ export interface POResult { - po: number[]; - spo: number[]; + poResult: number[]; + spoResult: number[]; } /** @@ -76,12 +76,15 @@ export function po( const pu = mmax(vHighs, { period }); const pl = mmin(vLows, { period }); - const po = divide(multiplyBy(100, subtract(closings, pl)), subtract(pu, pl)); - const spo = ema(po, { period: smooth }); + const poResult = divide( + multiplyBy(100, subtract(closings, pl)), + subtract(pu, pl) + ); + const spoResult = ema(poResult, { period: smooth }); return { - po, - spo, + poResult, + spoResult, }; } diff --git a/src/indicator/volume/index.md b/src/indicator/volume/README.md similarity index 52% rename from src/indicator/volume/index.md rename to src/indicator/volume/README.md index 4310641..c75d4f1 100644 --- a/src/indicator/volume/index.md +++ b/src/indicator/volume/README.md @@ -1,18 +1,23 @@ -### Volume Indicators +# Volume Indicators Volumne indicators measure the strength of a trend based the volume. -- [Accumulation/Distribution (A/D)](#accumulationdistribution-ad) -- [Chaikin Money Flow (CMF)](#chaikin-money-flow-cmf) -- [Ease of Movement (EMV)](#ease-of-movement-emv) -- [Force Index (FI)](#force-index-fi) -- [Money Flow Index (MFI)](#money-flow-index-mfi) -- [Negative Volume Index (NVI)](#negative-volume-index-nvi) -- [On-Balance Volume (OBV)](#on-balance-volume-obv) -- [Volume Price Trend (VPT)](#volume-price-trend-vpt) -- [Volume Weighted Average Price (VWAP)](#volume-weighted-average-price-vwap) +- [Volume Indicators](#volume-indicators) + - [Accumulation/Distribution (A/D)](#accumulationdistribution-ad) + - [Chaikin Money Flow (CMF)](#chaikin-money-flow-cmf) + - [Ease of Movement (EMV)](#ease-of-movement-emv) + - [Force Index (FI)](#force-index-fi) + - [Money Flow Index (MFI)](#money-flow-index-mfi) + - [Negative Volume Index (NVI)](#negative-volume-index-nvi) + - [On-Balance Volume (OBV)](#on-balance-volume-obv) + - [Volume Price Trend (VPT)](#volume-price-trend-vpt) + - [Volume Weighted Average Price (VWAP)](#volume-weighted-average-price-vwap) + - [Disclaimer](#disclaimer) + - [License](#license) -#### Accumulation/Distribution (A/D) +**NOTE:** All configuration objects for all indicators are optional. If no configuration object is passed, the default configuration will be used. Likewise, you may also partially pass a configuration object, and the default values will be used for the missing properties. + +## Accumulation/Distribution (A/D) The [accumulationDistribution](./accumulationDistribution.ts) is a cumulative indicator that uses volume and price to assess whether a stock is being accumulated or distributed. @@ -24,15 +29,18 @@ MFV = MFM * Period Volume AD = Previous AD + CMFV ``` -Based on [Accumulation/Distribution Indicator (A/D)](https://www.investopedia.com/terms/a/accumulationdistribution.asp). - ```TypeScript -import {accumulationDistribution} from 'indicatorts'; +import { ad } from 'indicatorts'; + +const result = ad(highs, lows, closings, volumes); -const result = accumulationDistribution(highs, lows, closings, volumes); +// Alternatively: +// const result = accumulationDistribution(highs, lows, closings, volumes); ``` -#### Chaikin Money Flow (CMF) +Based on [Accumulation/Distribution Indicator (A/D)](https://www.investopedia.com/terms/a/accumulationdistribution.asp). + +## Chaikin Money Flow (CMF) The [chaikinMoneyFlow](./chaikinMoneyFlow.ts) measures the amount of money flow volume over a given period. @@ -43,12 +51,16 @@ Chaikin Money Flow = Sum(20, Money Flow Volume) / Sum(20, Volume) ``` ```TypeScript -import {chaikinMoneyFlow} from 'indicatorts'; +import { cmf } from 'indicatorts'; -const result = chaikinMoneyFlow(highs, lows, closings, volumes); +const defaultConfig = { period: 20 }; +const result = cmf(highs, lows, closings, volumes, defaultConfig); + +// Alternatively: +// const result = chaikinMoneyFlow(highs, lows, closings, volumes, defaultConfig); ``` -#### Ease of Movement (EMV) +## Ease of Movement (EMV) The [easeOfMovement](./easeOfMovement.ts) is a volume based oscillator measuring the ease of price movement. @@ -60,12 +72,16 @@ EMV(14) = SMA(14, EMV(1)) ``` ```TypeScript -import {easeOfMovement} from 'indicatorts'; +import { emv } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const result = emv(highs, lows, volumes, defaultConfig); -const result = easeOfMovement(period, highs, lows, volumes); +// Alternatively: +// const result = easeOfMovement(highs, lows, volumes, defaultConfig); ``` -#### Force Index (FI) +## Force Index (FI) The [forceIndex](./forceIndex.ts) uses the closing price and the volume to assess the power behind a move and identify turning points. @@ -74,12 +90,16 @@ Force Index = EMA(period, (Current - Previous) * Volume) ``` ```TypeScript -import {forceIndex} from 'indicatorts'; +import { fi } from 'indicatorts'; -const result = forceIndex(period, closings, volumes); +const defaultConfig = { period: 13 }; +const result = fi(closings, volumes, defaultConfig); + +// Alternatively: +// const result = forceIndex(closings, volumes, defaultConfig); ``` -#### Money Flow Index (MFI) +## Money Flow Index (MFI) The [moneyFlowIndex](./moneyFlowIndex.ts) function analyzes both the closing price and the volume to measure to identify overbought and oversold states. It is similar to the Relative Strength Index (RSI), but it also uses the volume. @@ -90,14 +110,16 @@ Money Flow Index = 100 - (100 / (1 + Money Ratio)) ``` ```TypeScript -import {moneyFlowIndex} from 'indicatorts'; +import { mfi } from 'indicatorts'; -const result = moneyFlowIndex(14, highs, lows, closings, volumes); -``` +const defaultConfig = { period: 14 }; +const result = mfi(highs, lows, closings, volumes, defaultConfig); -The [defaultMoneyFlowIndex](./moneyFlowIndex.ts) function uses the default period of 14. +// Alternatively: +// const result = moneyFlowIndex(highs, lows, closings, volumes, defaultConfig); +``` -#### Negative Volume Index (NVI) +## Negative Volume Index (NVI) The [negativeVolumeIndex](./negativeVolumeIndex.ts) function calculates a cumulative indicator using the change in volume to decide when the smart money is active. @@ -112,12 +134,16 @@ Otherwise: ``` ```TypeScript -import {negativeVolumeIndex} from 'indicatorts'; +import { nvi } from 'indicatorts'; + +const defaultConfig = { start: 1000, period: 255 }; +const result = nvi(closings, volumes, defaultConfig); -const nvi = negativeVolumeIndex(closings, volumes); +// Alternatively: +// const result = negativeVolumeIndex(closings, volumes, defaultConfig); ``` -#### On-Balance Volume (OBV) +## On-Balance Volume (OBV) The [onBalanceVolume](./onBalanceVolume.ts) function calculates a technical trading momentum indicator that uses volume flow to predict changes in stock price. @@ -128,12 +154,15 @@ OBV = OBV-Prev + 0, if Closing = Closing-Prev ``` ```TypeScript -import {onBalanceVolume} from 'indicatorts'; +import {obv} from 'indicatorts'; -const result = onBalanceVolume(closings, volumes); +const result = obv(closings, volumes); + +// Alternatively: +// const result = onBalanceVolume(closings, volumes); ``` -#### Volume Price Trend (VPT) +## Volume Price Trend (VPT) The [volumePriceTrend](./volumePriceTrend.ts) provides a correlation between the volume and the price. @@ -142,12 +171,15 @@ VPT = Previous VPT + (Volume * (Current Closing - Previous Closing) / Previous C ``` ```TypeScript -import {volumePriceTrend} from 'indicatorts'; +import { vpt } from 'indicatorts'; + +const result = vpt(closings, volumes); -const result = volumePriceTrend(closings, volumes); +// Alternatively: +// const result = volumePriceTrend(closings, volumes); ``` -#### Volume Weighted Average Price (VWAP) +## Volume Weighted Average Price (VWAP) The [volumeWeightedAveragePrice](./volumeWeightedAveragePrice.ts) provides the average price the asset has traded. @@ -156,9 +188,13 @@ VWAP = Sum(Closing * Volume) / Sum(Volume) ``` ```TypeScript -import {volumeWeightedAveragePrice} from 'indicatorts'; +import { vwap } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const result = vwap(closings, volumes, defaultConfig); -const result = volumeWeightedAveragePrice(period, closings, volumes); +// Alternatively: +// const result = volumeWeightedAveragePrice(closings, volumes, defaultConfig); ``` ## Disclaimer diff --git a/src/strategy/index.md b/src/strategy/README.md similarity index 81% rename from src/strategy/index.md rename to src/strategy/README.md index 13d13e9..2c2e632 100644 --- a/src/strategy/index.md +++ b/src/strategy/README.md @@ -1,19 +1,22 @@ -### Strategies +# Strategies The strategies are where the results from one or more indicators gets combined to produce a recommended action. **The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security.** -- [Asset](#asset) - - [New Asset with Length](#new-asset-with-length) - - [Concat Assets](#concat-assets) -- [Action](#action) - - [Reverse Actions](#reverse-actions) - - [Apply Actions](#apply-actions) -- [Strategy Function](#strategy-function) -- [Buy and Hold Strategy](#buy-and-hold-strategy) +- [Strategies](#strategies) + - [Asset](#asset) + - [New Asset with Length](#new-asset-with-length) + - [Concat Assets](#concat-assets) + - [Strategy Function](#strategy-function) + - [Action](#action) + - [Reverse Actions](#reverse-actions) + - [Apply Actions](#apply-actions) + - [Buy and Hold Strategy](#buy-and-hold-strategy) + - [Disclaimer](#disclaimer) + - [License](#license) -#### Asset +## Asset The stragies operates on an [Asset](./asset.ts) with the following members. @@ -28,7 +31,7 @@ interface Asset { } ``` -##### New Asset with Length +### New Asset with Length The [newAssetWithLength](./asset.ts) function provides a new asset with each field initialized to the given length. @@ -41,7 +44,7 @@ asset.closings[0] = 10; asset.closings[1] = 20; ``` -##### Concat Assets +### Concat Assets The [concatAssets](./asset.ts) function concats the given two assets. @@ -51,7 +54,7 @@ import {concatAssets} from 'indicatorts'; const asset = concatAssets(asset1, asset2); ``` -#### Strategy Function +## Strategy Function The [StrategyFunction](./strategyFunction.ts) takes an [Asset](#asset), and provides an array of [Action](#action) for each row. @@ -59,7 +62,7 @@ The [StrategyFunction](./strategyFunction.ts) takes an [Asset](#asset), and prov type StrategyFunction = (asset: Asset) => Action[]; ``` -#### Action +## Action The following [Action](./action.ts) values are currently provided. @@ -71,7 +74,7 @@ enum Action { } ``` -##### Reverse Actions +### Reverse Actions The [reverseActions](./action.ts) function returns the reverse of the provided actions. @@ -92,7 +95,7 @@ const result = reverseActions(actions); // ]; ``` -##### Apply Actions +### Apply Actions The [applyActions](./action.ts) function applies the given actions to the given closings and provides the gains at each step. @@ -102,7 +105,7 @@ import {applyActions} from 'indicatorts'; const gains = applyActions(closings, actions); ``` -#### Buy and Hold Strategy +## Buy and Hold Strategy The [buyAndHoldStrategy](./buyAndHoldStrategy.ts) provides a simple strategy to buy the given asset and hold it. It provides a good indicator for the change of asset's value without any other strategy is used. diff --git a/src/strategy/momentum/README.md b/src/strategy/momentum/README.md new file mode 100644 index 0000000..2e0aae6 --- /dev/null +++ b/src/strategy/momentum/README.md @@ -0,0 +1,87 @@ +# Momentum Strategies + +Momentum strategies generate signals based on a momentum indicator. + +- [Momentum Strategies](#momentum-strategies) + - [Awesome Oscillator Strategy](#awesome-oscillator-strategy) + - [Ichimoku Cloud Strategy](#ichimoku-cloud-strategy) + - [RSI 2 Strategy](#rsi-2-strategy) + - [Stochastic Oscillator Strategy](#stochastic-oscillator-strategy) + - [Williams R Strategy](#williams-r-strategy) + - [Disclaimer](#disclaimer) + - [License](#license) + +**NOTE:** All configuration objects for all strategies are optional. If no configuration object is passed, the default configuration will be used. Likewise, you may also partially pass a configuration object, and the default values will be used for the missing properties. + +## Awesome Oscillator Strategy + +The [awesomeOscillatorStrategy](./awesomeOscillatorStrategy.ts) uses the _ao_ values that are generated by the [Awesome Oscillator](../../indicator/momentum/README.md#awesome-oscillator-ao) indicator function to provide a SELL action when the _ao_ is below zero, and a BUY action when _ao_ is above zero. + +```TypeScript +import { aoStrategy } from 'indicatorts'; + +const defaultConfig = { fast: 5, slow: 34 }; +const actions = aoStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = awesomeOscillatorStrategy(asset, defaultConfig); +``` + +## Ichimoku Cloud Strategy + +The [ichimokuCloudStrategy](./ichimokuCloudStrategy.ts) uses the _ao_ values that are generated by the [Ichimoku Cloud](../../indicator/momentum/README.md#ichimoku-cloud) indicator function to provide a _BUY_ action when the _leadingSpanA_ is greather than _leadingSpanB_, and a _SELL_ action when the _leadingSpanA_ is less than _leadingSpanB_, and a _HOLD_ action when _leadingSpanA_ is equal to _leadingSpanB_. + +```TypeScript +import { ichimokuCloudStrategy } from 'indicatorts'; + +const defaultConfig = { short: 9, medium: 26, long: 52, close: 26 }; +const actions = ichimokuCloudStrategy(asset, defaultConfig); +``` + +## RSI 2 Strategy + +The [rsi2Strategy](./rsi2Strategy.ts) uses the _rsi_ values that are generated by the [RSI 2](../../indicator/momentum/README.md#relative-strength-index-rsi) indicator function to provide a _BUY_ action when 2-period RSI moves below 10, and a _SELL_ action when the 2-period RSI moved above 90, and a _HOLD_ action otherwise. + +```TypeScript +import { rsi2Strategy } from 'indicatorts'; + +const actions = rsi2Strategy(asset); +``` + +## Stochastic Oscillator Strategy + +The [stochasticOscillatorStrategy](./stochasticOscillatorStrategy.ts) uses the _ao_ values that are generated by the [Stochastic Oscillator](../../indicator/momentum/README.md#stochastic-oscillator-stoch) indicator function to provide a _BUY_ action when _k_ and _d_ are less than 20, a _SELL_ action when the _k_ and _d_ are greather than 80, a _HOLD_ action otherwise. + +```TypeScript +import { stochStrategy } from 'indicatorts'; + +const defaultConfig = { kPeriod: 14, dPeriod: 3 }; +const actions = stochStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = stochasticOscillatorStrategy(asset, defaultConfig); +``` + +## Williams R Strategy + +The [williamsRStrategy](./williamsRStrategy.ts) uses the _wr_ values that are generated by the [Williams R](../../indicator/momentum/README.md#williams-r-willr) indicator function to provide a SELL action when the _wr_ is below -20, and a BUY action when _wr_ is above -80. + +```TypeScript +import { willRStrategy } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const actions = willRStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = williamsRStrategy(asset, defaultConfig); +``` + +## Disclaimer + +The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. + +## License + +Copyright (c) 2022 Onur Cinar. All Rights Reserved. + +The source code is provided under MIT License. diff --git a/src/strategy/momentum/index.md b/src/strategy/momentum/index.md deleted file mode 100644 index 7d1e823..0000000 --- a/src/strategy/momentum/index.md +++ /dev/null @@ -1,69 +0,0 @@ -### Momentum Strategies - -Momentum strategies generate signals based on a momentum indicator. - -- [Awesome Oscillator Strategy](#awesome-oscillator-strategy) -- [Ichimoku Cloud Strategy](#ichimoku-cloud-strategy) -- [RSI 2 Strategy](#rsi-2-strategy) -- [Stochastic Oscillator Strategy](#stochastic-oscillator-strategy) -- [Williams R Strategy](#williams-r-strategy) - -#### Awesome Oscillator Strategy - -The [awesomeOscillatorStrategy](./awesomeOscillatorStrategy.ts) uses the _ao_ values that are generated by the [Awesome Oscillator](../../indicator/momentum/index.md#awesome-oscillator) indicator function to provide a SELL action when the _ao_ is below zero, and a BUY action when _ao_ is above zero. - -```TypeScript -import {awesomeOscillatorStrategy} from 'indicatorts'; - -const actions = awesomeOscillatorStrategy(asset); -``` - -#### Ichimoku Cloud Strategy - -The [ichimokuCloudStrategy](./ichimokuCloudStrategy.ts) uses the _ao_ values that are generated by the [Ichimoku Cloud](../../indicator/momentum/index.md#ichimoku-cloud) indicator function to provide a _BUY_ action when the _leadingSpanA_ is greather than _leadingSpanB_, and a _SELL_ action when the _leadingSpanA_ is less than _leadingSpanB_, and a _HOLD_ action when _leadingSpanA_ is equal to _leadingSpanB_. - -```TypeScript -import {ichimokuCloudStrategy} from 'indicatorts'; - -const actions = ichimokuCloudStrategy(asset); -``` - -#### RSI 2 Strategy - -The [rsi2Strategy](./rsi2Strategy.ts) uses the _rsi_ values that are generated by the [RSI 2](../../indicator/momentum/index.md#rsi-2) indicator function to provide a _BUY_ action when 2-period RSI moves below 10, and a _SELL_ action when the 2-period RSI moved above 90, and a _HOLD_ action otherwise. - -```TypeScript -import {rsi2Strategy} from 'indicatorts'; - -const actions = rsi2Strategy(asset); -``` - -#### Stochastic Oscillator Strategy - -The [stochasticOscillatorStrategy](./ichimokuCloudStrategy.ts) uses the _ao_ values that are generated by the [Stochastic Oscillator](../../indicator/momentum/index.md#stochastic-oscillator) indicator function to provide a _BUY_ action when _k_ and _d_ are less than 20, a _SELL_ action when the _k_ and _d_ are greather than 80, a _HOLD_ action otherwise. - -```TypeScript -import {stochasticOscillatorStrategy} from 'indicatorts'; - -const actions = stochasticOscillatorStrategy(asset); -``` - -#### Williams R Strategy - -The [williamsRStrategy](./williamsRStrategy.ts) uses the _wr_ values that are generated by the [Williams R](../../indicator/momentum/index.md#williams-r) indicator function to provide a SELL action when the _wr_ is below -20, and a BUY action when _wr_ is above -80. - -```TypeScript -import {williamsRStrategy} from 'indicatorts'; - -const actions = williamsRStrategy(asset); -``` - -## Disclaimer - -The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. - -## License - -Copyright (c) 2022 Onur Cinar. All Rights Reserved. - -The source code is provided under MIT License. diff --git a/src/strategy/momentum/stochasticOscillatorStrategy.ts b/src/strategy/momentum/stochasticOscillatorStrategy.ts index 6296e2b..1263200 100644 --- a/src/strategy/momentum/stochasticOscillatorStrategy.ts +++ b/src/strategy/momentum/stochasticOscillatorStrategy.ts @@ -16,7 +16,10 @@ import { * @param config configuration. * @return strategy actions. */ -export function soStrategy(asset: Asset, config: StochConfig = {}): Action[] { +export function stochStrategy( + asset: Asset, + config: StochConfig = {} +): Action[] { const strategyConfig = { ...StochDefaultConfig, ...config }; const result = stoch(asset.highs, asset.lows, asset.closings, strategyConfig); @@ -36,4 +39,4 @@ export function soStrategy(asset: Asset, config: StochConfig = {}): Action[] { } // Export full name -export { soStrategy as stochasticOscillatorStrategy }; +export { stochStrategy as stochasticOscillatorStrategy }; diff --git a/src/strategy/trend/README.md b/src/strategy/trend/README.md new file mode 100644 index 0000000..1c9f5a3 --- /dev/null +++ b/src/strategy/trend/README.md @@ -0,0 +1,157 @@ +# Trend Strategies + +Trend strategies generate signals based on a trend indicator. + +- [Trend Strategies](#trend-strategies) + - [Absolute Price Oscillator Strategy](#absolute-price-oscillator-strategy) + - [Aroon Strategy](#aroon-strategy) + - [Balance of Power Strategy](#balance-of-power-strategy) + - [Chande Forecast Oscillator Strategy](#chande-forecast-oscillator-strategy) + - [KDJ Strategy](#kdj-strategy) + - [MACD Strategy](#macd-strategy) + - [Parabolic SAR Strategy](#parabolic-sar-strategy) + - [Typical Price Strategy](#typical-price-strategy) + - [Volume Weighted Moving Average (VWMA) Strategy](#volume-weighted-moving-average-vwma-strategy) + - [Vortex Strategy](#vortex-strategy) + - [Disclaimer](#disclaimer) + - [License](#license) + +**NOTE:** All configuration objects for all strategies are optional. If no configuration object is passed, the default configuration will be used. Likewise, you may also partially pass a configuration object, and the default values will be used for the missing properties. + +## Absolute Price Oscillator Strategy + +The [absolutePriceOscillatorStrategy](./absolutePriceOscillatorStrategy.ts) uses the values that are generated by the [Absolute Price Oscillator (APO)](../../indicator/trend/README.md#absolute-price-oscillator-apo) indicator to provide a _BUY_ action when the _AO_ is greather than zero, and _SELL_ action when _AO_ is less than zero, otherwise _HOLD_ action. + +```TypeScript +import { apoStrategy } from 'indicatorts'; + +const defaultConfig = { fast: 14, slow: 30 }; +const actions = apoStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = absolutePriceOscillatorStrategy(asset, defaultConfig); +``` + +## Aroon Strategy + +The [aroonStrategy](./aroonStrategy.ts) uses the values that are generated by the [Aroon Indicator](../../indicator/trend/README.md#aroon) to provide a _BUY_ action when the _up_ is greather than _down_, and _SELL_ action when _up_ is less than _down_, otherwise _HOLD_ action. + +```TypeScript +import { aroonStrategy } from 'indicatorts'; + +const defaultConfig = { period: 25 }; +const actions = aroonStrategy(asset, defaultConfig); +``` + +## Balance of Power Strategy + +The [balanceOfPowerStrategy](./balanceOfPowerStrategy.ts) uses the values that are generated by the [Balance of Power (BOP)](../../indicator/trend/README.md#balance-of-power-bop) indicator to provide a _BUY_ action when the _BOP_ is greather than zero, and _SELL_ action when _BOP_ is less than zero, otherwise _HOLD_ action. + +```TypeScript +import { bopStrategy } from 'indicatorts'; + +const actions = bopStrategy(asset); + +// Alternatively: +// const actions = balanceOfPowerStrategy(asset); +``` + +## Chande Forecast Oscillator Strategy + +The [chandeForecastOscillatorStrategy](./chandeForecastOscillatorStrategy.ts) uses _cfo_ values that are generated by the [Chande Forecast Oscillator (CFO)](../../indicator/trend/README.md#chande-forecast-oscillator-cfo) indicator function to provide a BUY action when _cfo_ is below zero, and SELL action when _cfo_ is above zero. + +```TypeScript +import { cfoStrategy } from 'indicatorts'; + +const actions = cfoStrategy(asset); + +// Alternatively: +// const actions = chandeForecastOscillatorStrategy(asset); +``` + +## KDJ Strategy + +The [kdjStrategy](./kdjStrategy.ts) function uses the _k_, _d_, _j_ values that are generated by the [Random Index (KDJ)](../../indicator/trend/README.md#random-index-kdj) indicator function to provide a BUY action when _k_ crosses above _d_ and _j_. It is stronger when below 20%. Also the SELL action is when _k_ crosses below _d_ and _j_. It is strong when above 80%. + +```TypeScript +import { kdjStrategy } from 'indicatorts'; + +const defaultConfig = { rPeriod: 9, kPeriod: 3, dPeriod: 3 }; +const actions = kdjStrategy(asset, defaultConfig); +``` + +## MACD Strategy + +The [macdStrategy](./macdStrategy.ts) uses the _macd_, and _signal_ values that are generated by the [Moving Average Convergence Divergence (MACD)](../../indicator/trend/README.md#moving-average-convergence-divergence-macd) indicator function to provide a BUY action when _macd_ crosses above _signal_, and SELL action when _macd_ crosses below _signal_. + +```TypeScript +import { macdStrategy } from 'indicatorts'; + +const defaultConfig = { fast: 12, slow: 26, signal: 9 }; +const actions = macdStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = movingAverageConvergenceDivergenceStrategy(asset, defaultConfig); +``` + +## Parabolic SAR Strategy + +The [parabolicSARStrategy](./parabolicSarStrategy.ts) uses the values that are generated by the [Parabolic SAR](../../indicator/trend/README.md#parabolic-sar-psar) indicator function to provide a _BUY_ action when the trend is _FALLING_, and _SELL_ action when the trend is _RISING_, and _HOLD_ action when the trend is _STABLE_. + +```TypeScript +import { psarStrategy } from 'indicatorts'; + +const defaultConfig = { step: 0.02, max: 0.2 }; +const actions = psarStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = parabolicSARStrategy(asset, defaultConfig); +``` + +## Typical Price Strategy + +The [typicalPriceStrategy](./typicalPriceStrategy.ts) uses the values that are generated by the [Typical Price](../../indicator/trend/README.md#typical-price) indicator function to provide a _BUY_ action when the value is greather than the previous value, and _SELL_ action when the value is less than the previous value, and _HOLD_ action when value is equal to the previous value. + +```TypeScript +import { typpriceStrategy } from 'indicatorts'; + +const actions = typpriceStrategy(asset); + +// Alternatively: +// const actions = typicalPriceStrategy(asset); +``` + +## Volume Weighted Moving Average (VWMA) Strategy + +The [vwmaStrategy](./vwmaStrategy.ts) function uses SMA and VWMA indicators to provide a _BUY_ action when VWMA is above SMA, and a _SELL_ signal when VWMA is below SMA, a _HOLD_ signal otherwse. + +```TypeScript +import { vwmaStrategy } from 'indicatorts'; + +const defaultConfig = { period: 20 }; +const actions = vwmaStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = volumeWeightedMovingAverageStrategy(asset, defaultConfig); +``` + +## Vortex Strategy + +The [vortexStrategy](./vortexStrategy.ts) uses the values that are generated by the [Vortex Indicator](../../indicator/trend/README.md#vortex-indicator) indicator function to provide a _BUY_ action when the _plusVi_ is greather than the _minusVi_, and _SELL_ action when the _plusVi_ is less than the _minusVi_, and _HOLD_ action when the _plusVi_ is equal to the _minusVi_. + +```TypeScript +import { vortexStrategy } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const actions = vortexStrategy(asset, defaultConfig); +``` + +## Disclaimer + +The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. + +## License + +Copyright (c) 2022 Onur Cinar. All Rights Reserved. + +The source code is provided under MIT License. diff --git a/src/strategy/trend/index.md b/src/strategy/trend/index.md deleted file mode 100644 index fa901e0..0000000 --- a/src/strategy/trend/index.md +++ /dev/null @@ -1,132 +0,0 @@ -### Trend Strategies - -Trend strategies generate signals based on a trend indicator. - -- [Absolute Price Oscillator Strategy](#absolute-price-oscillator-strategy) -- [Aroon Strategy](#aroon-strategy) -- [Balance of Power Strategy](#balance-of-power-strategy) -- [Chande Forecast Oscillator Strategy](#chande-forecast-oscillator-strategy) -- [MACD Strategy](#macd-strategy) -- [KDJ Strategy](#kdj-strategy) -- [Parabolic SAR Strategy](#parabolic-sar-strategy) -- [Typical Price Strategy](#typical-price-strategy) -- [Volume Weighted Moving Average (VWMA) Strategy](#volume-weighted-moving-average-vwma-strategy) -- [Vortex Strategy](#vortex-strategy) - -#### Absolute Price Oscillator Strategy - -The [absolutePriceOscillatorStrategy] uses the values that are generated by the [Absolute Price Oscillator (APO)](../../indicator/trend/index.md#absolute-price-oscillator-apo) indicator to provide a _BUY_ action when the _AO_ is greather than zero, and _SELL_ action when _AO_ is less than zero, otherwise _HOLD_ action. - -```TypeScript -import {absolutePriceOscillatorStrategy} from 'indicatorts'; - -const actions = absolutePriceOscillatorStrategy(asset, { fast: 14, slow: 30 }); -``` - -#### Aroon Strategy - -The [aroonStrategy](./aroonStrategy.ts) uses the values that are generated by the [Aroon Indicator](../../indicator/trend/index.md#aroon-indicator) to provide a _BUY_ action when the _up_ is greather than _down_, and _SELL_ action when _up_ is less than _down_, otherwise _HOLD_ action. - -```TypeScript -import {aroonStrategy} from 'indicatorts'; - -const actions = aroonStrategy(asset); -``` - -#### Balance of Power Strategy - -The [balanceOfPowerStrategy](./balanceOfPowerStrategy.ts) uses the values that are generated by the [Balance of Power (BOP)](../../indicator/trend/index.md#balance-of-power-bop) indicator to provide a _BUY_ action when the _BOP_ is greather than zero, and _SELL_ action when _BOP_ is less than zero, otherwise _HOLD_ action. - -```TypeScript -import {balanceOfPowerStrategy} from 'indicatorts'; - -const actions = balanceOfPowerStrategy(asset); -``` - -#### Chande Forecast Oscillator Strategy - -The [chandeForecastOscillatorStrategy](./chandeForecastOscillatorStrategy.ts) uses _cfo_ values that are generated by the [Chande Forecast Oscillator (CFO)](../../indicator/trend/index.md#chande-forecast-oscillator-cfo) indicator function to provide a BUY action when _cfo_ is below zero, and SELL action when _cfo_ is above zero. - -```TypeScript -import {chandeForecastOscillatorStrategy} from 'indicatorts'; - -const actions = chandeForecastOscillatorStrategy(asset); -``` - -#### KDJ Strategy - -The [kdjStrategy](./kdjStrategy.ts) function uses the _k_, _d_, _j_ values that are generated by the [Random Index (KDJ)](../../indicator/trend/index.md#random-index-kdj) indicator function to provide a BUY action when _k_ crosses above _d_ and _j_. It is stronger when below 20%. Also the SELL action is when _k_ crosses below _d_ and _j_. It is strong when above 80%. - -```TypeScript -import {kdjStrategy} from 'indicatorts'; - -const actions = kdjStrategy(asset); -``` - -#### MACD Strategy - -The [macdStrategy](./macdStrategy.ts) uses the _macd_, and _signal_ values that are generated by the [Moving Average Convergence Divergence (MACD)](../../indicator/trend/index.md#moving-average-convergence-divergence-macd) indicator function to provide a BUY action when _macd_ crosses above _signal_, and SELL action when _macd_ crosses below _signal_. - -```TypeScript -import {macdStrategy} from 'indicatorts'; - -const actions = macdStrategy(asset); -``` - -#### Parabolic SAR Strategy - -The [parabolicSarStrategy](./parabolicSarStrategy.ts) uses the values that are generated by the [Parabolic SAR](../../indicator/trend/index.md#parabolic-sar) indicator function to provide a _BUY_ action when the trend is _FALLING_, and _SELL_ action when the trend is _RISING_, and _HOLD_ action when the trend is _STABLE_. - -```TypeScript -import {parabolicSarStrategy} from 'indicatorts'; - -const actions = parabolicSarStrategy(asset); -``` - -#### Typical Price Strategy - -The [typicalPriceStrategy](./typicalPriceStrategy.ts) uses the values that are generated by the [Typical Price](../../indicator/trend/index.md#typical-price) indicator function to provide a _BUY_ action when the value is greather than the previous value, and _SELL_ action when the value is less than the previous value, and _HOLD_ action when value is equal to the previous value. - -```TypeScript -import {typicalPriceStrategy} from 'indicatorts'; - -const actions = typicalPriceStrategy(asset); -``` - -#### Volume Weighted Moving Average (VWMA) Strategy - -The [vwmaStrategy](./vwmaStrategy.ts) function uses SMA and VWMA indicators to provide a _BUY_ action when VWMA is above SMA, and a _SELL_ signal when VWMA is below SMA, a _HOLD_ signal otherwse. - -```TypeScript -import { vwmaStrategy } from 'indicatorts'; - -const actions = vwmaStrategy(period, asset); -``` - -The [defaultVwmaStrategy](./vwmaStrategy.ts) function can be used with the default period of 20. - -```TypeScript -import { defaultVwmaStrategy } from 'indicatorts'; - -const actions = defaultVwmaStrategy(asset); -``` - -#### Vortex Strategy - -The [vortexStrategy](./vortexStrategy.ts) uses the values that are generated by the [Vortex Indicator](../../indicator/trend/index.md#vortex-indicator) indicator function to provide a _BUY_ action when the _plusVi_ is greather than the _minusVi_, and _SELL_ action when the _plusVi_ is less than the _minusVi_, and _HOLD_ action when the _plusVi_ is equal to the _minusVi_. - -```TypeScript -import {vortexStrategy} from 'indicatorts'; - -const actions = vortexStrategy(asset); -``` - -## Disclaimer - -The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. - -## License - -Copyright (c) 2022 Onur Cinar. All Rights Reserved. - -The source code is provided under MIT License. diff --git a/src/strategy/trend/kdjStrategy.ts b/src/strategy/trend/kdjStrategy.ts index 4332206..022ed4f 100644 --- a/src/strategy/trend/kdjStrategy.ts +++ b/src/strategy/trend/kdjStrategy.ts @@ -3,7 +3,11 @@ import { Asset } from '../asset'; import { Action } from '../action'; -import { KDJConfig, KDJDefaultConfig, kdj } from '../../indicator/trend/kdj'; +import { + KDJConfig, + KDJDefaultConfig, + kdj, +} from '../../indicator/trend/randomIndex'; /** * KDJ strategy. diff --git a/src/strategy/trend/macdStrategy.ts b/src/strategy/trend/macdStrategy.ts index 06f3f0a..105e8e8 100644 --- a/src/strategy/trend/macdStrategy.ts +++ b/src/strategy/trend/macdStrategy.ts @@ -18,12 +18,12 @@ import { export function macdStrategy(asset: Asset, config: MACDConfig = {}): Action[] { const strategyConfig = { ...MACDDefaultConfig, ...config }; const result = macd(asset.closings, strategyConfig); - const actions = new Array(result.macd.length); + const actions = new Array(result.macdLine.length); for (let i = 0; i < actions.length; i++) { - if (result.macd[i] > result.signal[i]) { + if (result.macdLine[i] > result.signalLine[i]) { actions[i] = Action.BUY; - } else if (result.macd[i] < result.signal[i]) { + } else if (result.macdLine[i] < result.signalLine[i]) { actions[i] = Action.SELL; } else { actions[i] = Action.HOLD; diff --git a/src/strategy/volatility/README.md b/src/strategy/volatility/README.md new file mode 100644 index 0000000..d6365c4 --- /dev/null +++ b/src/strategy/volatility/README.md @@ -0,0 +1,64 @@ +# Volatility Strategies + +Volatility strategies generate signals based on a volatility indicator. + +- [Volatility Strategies](#volatility-strategies) + - [Acceleration Bands Strategy](#acceleration-bands-strategy) + - [Bollinger Bands Strategy](#bollinger-bands-strategy) + - [Projection Oscillator Strategy](#projection-oscillator-strategy) + - [Disclaimer](#disclaimer) + - [License](#license) + +**NOTE:** All configuration objects for all strategies are optional. If no configuration object is passed, the default configuration will be used. Likewise, you may also partially pass a configuration object, and the default values will be used for the missing properties. + +## Acceleration Bands Strategy + +The [accelerationBandsStrategy](./accelerationBandsStrategy.ts) uses the _upperBand_, and _lowerBand_ values that are generated by the [Acceleration Bands](../../indicator/volatility/README.md#acceleration-bands-ab) indicator function to provide a _BUY_ action when closing is greather than or equals to _upperBand_, a _SELL_ action otherwise. + +```TypeScript +import { abStrategy } from 'indicatorts'; + +const defaultConfig = { period: 20, multiplier: 4 }; +const actions = abStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = accelerationBandsStrategy(asset, defaultConfig); +``` + +## Bollinger Bands Strategy + +The [bollingerBandsStrategy](./bollingerBandsStrategy.ts) uses the _upperBand_, and _lowerBand_ values that are generated by the [Bollinger Bands](../../indicator/volatility/README.md#bollinger-bands-bb) indicator function to provide a _SELL_ action when the asset's closing is above the _upperBand_, and a _BUY_ action when the asset's closing is below the _lowerBand_ values, a _HOLD_ action otherwise. + +```TypeScript +import { bbStrategy } from 'indicatorts'; + +const defaultConfig = { period: 20 }; +const actions = bbStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = bollingerBandsStrategy(asset, defaultConfig); +``` + +## Projection Oscillator Strategy + +The [projectionOscillatorStrategy](./projectionOscillatorStrategy.ts) uses _po_ and _spo_ values that are generated by the [Projection Oscillator (PO)](../../indicator/volatility/README.md#projection-oscillator-po) indicator function to provide a BUY action when _po_ is above _spo_, and SELL action when _po_ is below _spo_. + +```TypeScript +import { poStrategy } from 'indicatorts'; + +const defaultConfig = { period: 14, smooth: 3 }; +const actions = poStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = projectionOscillatorStrategy(asset, defaultConfig); +``` + +## Disclaimer + +The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. + +## License + +Copyright (c) 2022 Onur Cinar. All Rights Reserved. + +The source code is provided under MIT License. diff --git a/src/strategy/volatility/index.md b/src/strategy/volatility/index.md deleted file mode 100644 index bfaa815..0000000 --- a/src/strategy/volatility/index.md +++ /dev/null @@ -1,47 +0,0 @@ -### Volatility Strategies - -Volatility strategies generate signals based on a volatility indicator. - -- [Acceleration Bands Strategy](#acceleration-bands-strategy) -- [Bollinger Bands Strategy](#bollinger-bands-strategy) -- [Projection Oscillator Strategy](#projection-oscillator-strategy) - -#### Acceleration Bands Strategy - -The [accelerationBandsStrategy](./accelerationBandsStrategy.ts) uses the _upperBand_, and _lowerBand_ values that are generated by the [Acceleration Bands](../../indicator/volatility/index.md#acceleration-bands) indicator function to provide a _BUY_ action when closing is greather than or equals to _upperBand_, a _SELL_ action otherwise. - -```TypeScript -import {accelerationBandsStrategy} from 'indicatorts'; - -const actions = accelerationBandsStrategy(asset); -``` - -#### Bollinger Bands Strategy - -The [bollingerBandsStrategy](./bollingerBandsStrategy.ts) uses the _upperBand_, and _lowerBand_ values that are generated by the [Bollinger Bands](../../indicator/volatility/index.md#bollinger-bands) indicator function to provide a _SELL_ action when the asset's closing is above the _upperBand_, and a _BUY_ action when the asset's closing is below the _lowerBand_ values, a _HOLD_ action otherwise. - -```TypeScript -import {bollingerBandsStrategy} from 'indicatorts'; - -const actions = bollingerBandsStrategy(asset); -``` - -#### Projection Oscillator Strategy - -The [projectionOscillatorStrategy](./projectionOscillatorStrategy.ts) uses _po_ and _spo_ values that are generated by the [Projection Oscillator (PO)](../../indicator/volatility/index.md#projection-oscillator-po) indicator function to provide a BUY action when _po_ is above _spo_, and SELL action when _po_ is below _spo_. - -```TypeScript -import {projectionOscillatorStrategy} from 'indicatorts'; - -const actions = projectionOscillatorStrategy(asset); -``` - -## Disclaimer - -The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. - -## License - -Copyright (c) 2022 Onur Cinar. All Rights Reserved. - -The source code is provided under MIT License. diff --git a/src/strategy/volatility/projectionOscillatorStrategy.ts b/src/strategy/volatility/projectionOscillatorStrategy.ts index 3d37111..db08f7d 100644 --- a/src/strategy/volatility/projectionOscillatorStrategy.ts +++ b/src/strategy/volatility/projectionOscillatorStrategy.ts @@ -20,12 +20,12 @@ export function poStrategy(asset: Asset, config: POConfig = {}): Action[] { const strategyConfig = { ...PODefaultConfig, ...config }; const result = po(asset.highs, asset.lows, asset.closings, strategyConfig); - const actions = new Array(result.po.length); + const actions = new Array(result.poResult.length); for (let i = 0; i < actions.length; i++) { - if (result.po[i] > result.spo[i]) { + if (result.poResult[i] > result.spoResult[i]) { actions[i] = Action.BUY; - } else if (result.po[i] < result.spo[i]) { + } else if (result.poResult[i] < result.spoResult[i]) { actions[i] = Action.SELL; } else { actions[i] = Action.HOLD; diff --git a/src/strategy/volume/README.md b/src/strategy/volume/README.md new file mode 100644 index 0000000..88eaefa --- /dev/null +++ b/src/strategy/volume/README.md @@ -0,0 +1,109 @@ +# Volume Strategies + +Momentum strategies generate signals based on a momentum indicator. + +- [Volume Strategies](#volume-strategies) + - [Chaikin Money Flow Strategy](#chaikin-money-flow-strategy) + - [Ease of Movement Strategy](#ease-of-movement-strategy) + - [Force Index Strategy](#force-index-strategy) + - [Money Flow Index Strategy](#money-flow-index-strategy) + - [Negative Volume Index Strategy](#negative-volume-index-strategy) + - [Volume Weighted Average Price Strategy](#volume-weighted-average-price-strategy) + - [Disclaimer](#disclaimer) + - [License](#license) + +**NOTE:** All configuration objects for all strategies are optional. If no configuration object is passed, the default configuration will be used. Likewise, you may also partially pass a configuration object, and the default values will be used for the missing properties. + +## Chaikin Money Flow Strategy + +The [chaikinMoneyFlowStrategy](./chaikinMoneyFlowStrategy.ts) uses the _cmf_ values that are generated by the [Chaikin Money Flow (CMF)](../../indicator/volume/README.md#chaikin-money-flow-cmf) indicator function to provide a _BUY_ action when _cmf_ is less than zero, a _SELL_ action when _cmf_ is greather than zero, a _HOLD_ action otherwise. + +```TypeScript +import { cmfStrategy } from 'indicatorts'; + +const defaultConfig = { period: 20 }; +const actions = cmfStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = chaikinMoneyFlowStrategy(asset, defaultConfig); +``` + +## Ease of Movement Strategy + +The [easeOfMovementStrategy](./easeOfMovementStrategy.ts) uses the _emv_ values that are generated by the [Ease of Movement (EMV)](../../indicator/volume/README.md#ease-of-movement-emv) indicator function to provide a _BUY_ action when _emv_ is greather than zero, and a _SELL_ action when _emv_ is less than zero, a _HOLD_ action otherwise. + +```TypeScript +import { emvStrategy } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const actions = emvStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = easeOfMovementStrategy(asset, defaultConfig); +``` + +## Force Index Strategy + +The [forceIndexStrategy](./forceIndexStrategy.ts) uses the _fi_ values that are generated by the [Force Index (FI)](../../indicator/volume/README.md#force-index-fi) indicator function to provide a _BUY_ action when _fi_ is greather than zero, and a _SELL_ action when _fi_ is less than zero, a _HOLD_ action otherwise. + +```TypeScript +import { fiStrategy } from 'indicatorts'; + +const defaultConfig = { period: 13 }; +const actions = fiStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = forceIndexStrategy(asset, defaultConfig); +``` + +## Money Flow Index Strategy + +The [moneyFlowIndexStrategy](./moneyFlowIndexStrategy.ts) uses the _mfi_ values that are generated by the [Money Flow Index (MFI)](../../indicator/volume/README.md#money-flow-index-mfi) indicator function to provide a _SELL_ action when _mfi_ is greather than or equal to 80, and a _BUY_ action when _mfi_ is less than or equal to 20. + +```TypeScript +import { mfiStrategy } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const actions = mfiStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = moneyFlowIndexStrategy(asset, defaultConfig); +``` + +## Negative Volume Index Strategy + +The [negativeVolumeIndexStrategy](./negativeVolumeIndexStrategy.ts) uses the _nvi_ values that are generated by the [Negative Volume Index (NVI)](../../indicator/volume/README.md#negative-volume-index-nvi) indicator function to provide a _BUY_ action when _nvi_ is less than its 255-period EMA, and a _SELL_ action when it is greather than its 255-period EMA, otherwise a _HOLD_ action. + +```TypeScript +import { nviStrategy } from 'indicatorts'; + +const defaultConfig = { start: 1000, period: 255 }; +const actions = nviStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = negativeVolumeIndexStrategy(asset, defaultConfig); +``` + +## Volume Weighted Average Price Strategy + +The [volumeWeightedAveragePriceStrategy](./volumeWeightedAveragePriceStrategy.ts) uses the values that are generated by the [Volume Weighted Average Price (VWAP)](../../indicator/volume/README.md#volume-weighted-average-price-vwap) indicator function to provide a _BUY_ action when the _closing_ is below the _VWAP_, and a _SELL_ action when the _closing_ is below the _VWAP_, a _HOLD_ action otherwise. + +```TypeScript +import { vwapStrategy } from 'indicatorts'; + +const defaultConfig = { period: 14 }; +const actions = vwapStrategy(asset, defaultConfig); + +// Alternatively: +// const actions = volumeWeightedAveragePriceStrategy(asset, defaultConfig); +``` + +## Disclaimer + +The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. + +## License + +Copyright (c) 2022 Onur Cinar. All Rights Reserved. + +The source code is provided under MIT License. diff --git a/src/strategy/volume/index.md b/src/strategy/volume/index.md deleted file mode 100644 index 5d993db..0000000 --- a/src/strategy/volume/index.md +++ /dev/null @@ -1,80 +0,0 @@ -### Volume Strategies - -Momentum strategies generate signals based on a momentum indicator. - -- [Chaikin Money Flow Strategy](#chaikin-money-flow-strategy) -- [Ease of Movement Strategy](#ease-of-movement-strategy) -- [Force Index Strategy](#force-index-strategy) -- [Money Flow Index Strategy](#money-flow-index-strategy) -- [Negative Volume Index Strategy](#negative-volume-index-strategy) -- [Volume Weighted Average Price Strategy](#volume-weighted-average-price-strategy) - -#### Chaikin Money Flow Strategy - -The [chaikinMoneyFlowStrategy](./chaikinMoneyFlowStrategy.ts) uses the _cmf_ values that are generated by the [Chaikin Money Flow (CMF)](../../indicator/volume/index.md#chaikin-money-flow-cmf) indicator function to provide a _BUY_ action when _cmf_ is less than zero, a _SELL_ action when _cmf_ is greather than zero, a _HOLD_ action otherwise. - -```TypeScript -import {chaikinMoneyFlowStrategy} from 'indicatorts'; - -const actions = chaikinMoneyFlowStrategy(asset); -``` - -#### Ease of Movement Strategy - -The [easeOfMovementStrategy](./easeOfMovementStrategy.ts) uses the _emv_ values that are generated by the [Ease of Movement (EMV)](../../indicator/volume/index.md#ease-of-movement-emv) indicator function to provide a _BUY_ action when _emv_ is greather than zero, and a _SELL_ action when _emv_ is less than zero, a _HOLD_ action otherwise. - -```TypeScript -import {easeOfMovementStrategy} from 'indicatorts'; - -const actions = easeOfMovementStrategy(asset); -``` - -#### Force Index Strategy - -The [forceIndexStrategy](./forceIndexStrategy.ts) uses the _fi_ values that are generated by the [Force Index (FI)](../../indicator/volume/index.md#force-index-fi) indicator function to provide a _BUY_ action when _fi_ is greather than zero, and a _SELL_ action when _fi_ is less than zero, a _HOLD_ action otherwise. - -```TypeScript -import {forceIndexStrategy} from 'indicatorts'; - -const actions = forceIndexStrategy(asset); -``` - -#### Money Flow Index Strategy - -The [moneyFlowIndexStrategy](./moneyFlowIndexStrategy.ts) uses the _mfi_ values that are generated by the [Money Flow Index (MFI)](../../indicator/volume/index.md#money-flow-index-mfi) indicator function to provide a _SELL_ action when _mfi_ is greather than or equal to 80, and a _BUY_ action when _mfi_ is less than or equal to 20. - -```TypeScript -import {moneyFlowIndexStrategy} from 'indicatorts'; - -const actions = moneyFlowIndexStrategy(asset); -``` - -#### Negative Volume Index Strategy - -The [negativeVolumeIndexStrategy](./negativeVolumeIndexStrategy.ts) uses the _nvi_ values that are generated by the [Negative Volume Index (NVI)](../../indicator/volume/index.md#negative-volume-index-nvi) indicator function to provide a _BUY_ action when _nvi_ is less than its 255-period EMA, and a _SELL_ action when it is greather than its 255-period EMA, otherwise a _HOLD_ action. - -```TypeScript -import {negativeVolumeIndexStrategy} from 'indicatorts'; - -const actions = negativeVolumeIndexStrategy(asset); -``` - -#### Volume Weighted Average Price Strategy - -The [volumeWeightedAveragePriceStrategy](./volumeWeightedAveragePriceStrategy.ts) uses the values that are generated by the [Volume Weighted Average Price (VWAP)](../../indicator/volume/index.md#volume-weighted-average-price-vwap) indicator function to provide a _BUY_ action when the _closing_ is below the _VWAP_, and a _SELL_ action when the _closing_ is below the _VWAP_, a _HOLD_ action otherwise. - -```TypeScript -import {volumeWeightedAveragePriceStrategy} from 'indicatorts'; - -const actions = volumeWeightedAveragePriceStrategy(asset); -``` - -## Disclaimer - -The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security. - -## License - -Copyright (c) 2022 Onur Cinar. All Rights Reserved. - -The source code is provided under MIT License.