Finding Exponential Moving Averages (EMA) with the power of JavaScript

Can EMA be calculated using JavaScript?

I am attempting to apply the following formula for EMA:

EMA = array[i] * K + EMA(previous) * (1 – K)

Where K represents the smooth factor:

K = 2/(N + 1)

And N is the range of values that I want to consider

If I have an array of values like this, where the values increase over time:

var data = [15,18,12,14,16,11,6,18,15,16];

The objective is to create a function that can return the array of EMAs. Each value in the array, except the very first "range" value, will have a corresponding EMA. By having the related EMA value for each item in the data array, I can either use all of them or just the last one to predict the next value.

function calculateEMA(array, range) {
var k = 2/(range + 1);
...
}

I'm struggling to implement this function and would appreciate any assistance.

Answer №1

It seems like you're looking for a function that calculates the Exponential Moving Average (EMA) for each index greater than 0 in an array. The first index will return the same value as the input array.

function calculateEMA(inputArray, range) {
  var k = 2 / (range + 1);
  // Initialize the EMA array with the first item from the input
  var emaArray = [inputArray[0]];
  
  // Calculate EMA for remaining items based on previous values
  for (var i = 1; i < inputArray.length; i++) {
    emaArray.push(inputArray[i] * k + emaArray[i - 1] * (1 - k));
  }
  
  return emaArray;
}

This code snippet should help you achieve your goal.

Answer №2

Here is an alternative approach to implementing the EMA.

const calculateEMA = (arr, range) => arr.reduce((prevArr, currVal, index) => {
  return index ? prevArr.concat(2 * currVal / (range + 1) + prevArr[prevArr.length - 1] * (range - 1) / (range + 1)) : prevArr;
}, [arr[0]]);
      
const dataArr = [15, 18, 12, 14, 16, 11, 6, 18, 15, 16];
const emaRange = 3;

console.log(calculateEMA(dataArr, emaRange));

Answer №3

Recursion is a fascinating concept, and I find it particularly intriguing when applied to EMA functions. Forget about managing arrays with this example.

function calculateMultiplier(N) { return 2 / (N + 1) }

function exponentialMovingAverage(tIndex, N, data) {
    if (!data[tIndex-1] || (tIndex) - (N) < 0) return undefined;
    const multiplier = calculateMultiplier(N);
    const currentPrice = data[tIndex];
    const previousEMA = exponentialMovingAverage(tIndex-1, N, data) || data[tIndex-1]
    return (currentPrice - previousEMA) * multiplier + yEMA
}

Answer №4

I wanted to provide a fresh perspective on the calculation method used in technical analysis and indicators like Binance and TradingView.

In this approach, the Simple Moving Average (SMA) serves as the initial step in deriving the Exponential Moving Average (EMA).

When analyzing a series of candles, ticks, or prices within a period or interval of 5, the process unfolds as follows:

  • 1st Tick - undefined
  • 2nd Tick - undefined
  • 3rd Tick - undefined
  • 4th Tick - undefined
  • 5th Tick - SMA (sum of first 5 ticks / period)
  • 6th Tick - EMA (((price - prevEMA) * exponent) + prevEMA)

To calculate the Exponential Moving Average for technical analysis:

const calcEMA = (prices) => {
  let sum = 0
    let averages = []
    let prevEMA = undefined
    let tickIndex = 1

    for (const price of prices) {

      if (tickIndex < period) {
        tickIndex++
          sum = sum + price
          averages.push(undefined)
      } else {

        if (prevEMA) {
          // EMA
          prevEMA = ((price - prevEMA) * exponent) + prevEMA
        } else {
          // SMA
          prevEMA = ((sum + price) / period)
        }

        averages.push(prevEMA)

      }
    }
  return averages
}

calcEMA([
    81.59, 81.06, 82.87, 83.0, 83.61, 83.15, 82.84, 83.99, 84.55, 84.36, 85.53, 86.54, 86.89, 87.77, 87.29,
])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Webpack is throwing an error stating that it cannot find a module with the relative path specified

Here is the structure of my app (excluding the node_modules directory): ├── actions.js ├── bundle.js ├── components │   ├── App.js │   ├── Footer.js │   ├── Link.js │   ├── Todo.js │   └─ ...

Ways to adjust brightness of a color using jquery

I have implemented color swatches and a slider to adjust the lightness and darkness of colors. I am seeking a way to change the lightness of the color based on the slider value. Here is what I have attempted: $("#darklight").slider({ range: "min", ...

What is the best way to bend a Polyline in react-google-maps?

Just dipping my toes into React and experimenting with the react-google-maps package. I'm on a mission to curve a Polyline connecting two locations. I've reviewed the documentation and I'm attempting to integrate the curve polyline function ...

Upgrading an Express 2.x application to Express 3.0

I am currently studying NodeJs and Express and am in the process of converting a tutorial app from Express 2.5.9 to version 3.0. The following code is now causing an error "500 Error: Failed to lookup view "views/login". How can I update this to render cor ...

The alignment issue persists when attempting to set 'relative' on the parent and 'absolute' on the inner element in a Bootstrap column for bottom alignment

Here is a snippet of my basic HTML code: <div class = "row"> <div class = "col-xs-8"> <p>long long long long text that generates a taller column</p> </div> <div class = "col-xs-4"> <p> ...

Internet Explorer 11 and the process of URL encoding

Hello there! I am currently working on an MVC project with Angular where I am utilizing a JsonResult to return JSON data from a list containing emails with a specific date. Below is the AJAX call I'm making from Angular: myApp.service('mailServ ...

How to Use Framer Motion in Next.js for window.innerWidth Less Than 768

I am trying to use window.innerWidth to control the timing of an animation (Framer Motion) in my Next.js project, but I keep encountering the error message: ReferenceError: window is not defined Here's a simplified version of my ValuesSection.jsx co ...

Vue.js and Firestore will only update variables that do not have empty string values

Modify the variables that are not empty strings const state = reactive({ birthNumber: '', phoneNumber: '', DoctorName: '', DoctorPhone: '', }) db.collection(state.user.uid).doc( ...

Ways to remove an item from firebase database

Currently, I am exploring ways to delete data stored in the Firebase database specifically under the requests category. Check out this example Below are the functions I have implemented to fetch and manipulate the data: export default { async contactArtis ...

A guide on plotting values from an array using Pinescript

Struggling to plot values from an array individually. How can I create a series to plot them? // © SKnight79 //@version=4 study("My Script") pma1 = array.new_float(5,0) array.push(pma1, security(syminfo.tickerid, "", (ema(close, 1 ...

Using HTML and JavaScript to choose relatives from the extended family: Uncles and Aunts

Looking for a better way to target elements in your HTML code? <div class="chunk" id=""> <div class="chunkContent"> <div class="textLeft" ></div> <div class="textRight" ></div> <div class= ...

Is it possible to display an unordered list upon clicking a button without relying on CSS and still achieve identical visual outcomes?

Within the responsive CSS of my web application, I am attempting to display the ul element inside the "mobile header" only upon clicking the "Connect Wallet" button. I want it to appear and disappear again as soon as anything else is clicked. Is there a w ...

What is causing this unique component to be positioned outside of the <tr> tag?

table.vue ... <tbody class="table-body"> <slot></slot> </tbody> ... TableCellRow.vue <template> <td class="table-row-cell" :class="this.class"> <s ...

Determine the execution time of a Python script

I have developed a series of Python scripts to run as the backend of my application. Users are required to upload a file using the provided webpage, where they can track the progress through a displayed progress bar. The file is broken down into frames, ob ...

Whenever I create the code using javascript, padding seems to always show up

I have a basic stacked row layout that displays an upper box and lower box without any padding. <span id="route" class="small"> <div class="row" style="border-style:solid;"> <div class="col-md-12 col-12"> <p>UpperBox</p& ...

Guide to monitoring updates to a universal server-side variable in Angular 2

I am currently developing an application using Angular 2 with Electron and Node. The tests are executed on the server, and the results are stored in a global variable array named testResults. I am able to access this array in Angular by using: declare var ...

Arrange the select default option using AngularJS as the first option

I've been working on a project using Angular where I fetch data from a JSON file and push it to an array object. This data is then displayed in the options of a select element. My issue is: The default option with selection appears first, but I only ...

I am finding the event naming conventions in Vue 3 to be quite perplex

In the parent component, there is a child component: <upsetting-moment-step :this-step-number="1" :current-step-number="currentStepNumber" @showNextStep="showNextStep" ></upsetting-moment-step> The par ...

Ways to extract certain characters from each element in an array

I'm attempting to make the first four characters of each element in an array (specifically a list) bold, but I am only able to select entire strings: $("li").slice(0).css("font-weight", "Bold"); Is there a way for me to indicate which characters wit ...

How to adjust transparency in Three.js objects

Currently, I am developing a scene where certain elements are loaded from a JSON file. While I am able to toggle the visibility of each individual object, I now find myself wanting to adjust the opacity/transparency of an individual object. The objects in ...