Calculating Indicators

Overview



Starting from a raw data set, you will likely need to calculate a set of indicators that you will use to calculate trades. Typically, you will just add those indicators onto the price records that you have.

this page discusses methods of coding indicators and appending those values to your price dataset. For a basic introduction to Javascript, please see Javascript Introduction

Scripting Indicators



A standard way to append data onto each record in a dataset is to use the map method.


prices = prices.map((p,i,data)=>{
  return {
    ...p,
    indicator://do some calculation here
  }
});
					


As easy as this may be, it still will involve some work, and can be slow.

AS an example, the following will calculate a 10 period moving average of the close


prices = prices.map((p,i,data)=>{
  return {
    ...p,
    movingAverage: $list(data).window(i-10,i).map(p=>p.close).average()
  }
});
					


An optimizd way to accomplish the same effect uses the $list.amap function. In addition to being optimized for speed, this hides the implementation details of calculating the average in the moving average module. While a moving average is simple to calculate, for other more complex indicators, this becomes very useful.


let ma = await import('/lib/time-series/moving-average/v1.0.0/moving-average.mjs');

let prices = [
	{date:'2000-01-01', price:100, id:'IBM'},
	{date:'2000-01-02', price:101, id:'IBM'},
	{date:'2000-01-03', price:102, id:'IBM'},
	{date:'2000-01-04', price:103, id:'IBM'},
	{date:'2000-01-05', price:104, id:'IBM'},
  ];

prices = $list(prices).amap(p=>p.price, {
  ma:data=>ma.movingAverage(data, 3)
}).items;

					
Try it!


With amap, you can easily add multliple indicators at a time.


let ma = await import('/lib/time-series/moving-average/v1.0.0/moving-average.srs.mjs');

prices = $list(prices).amap(p=>p.price, {
  ma10:ma.movingAverage(10),
  ma50:ma.movingAverage(50)
}).items;

					


Note that when adding an indicator, you must be cognizant of the assumptions built into the indicator you are using. For instance, the moving average indicator assumes that the dataset is sorted by date. That is, you only want to calculate the moving average of the prices just prior to the current price. If the dataset is not sorted, you may have to sort the dataset first.

Datasets With Multiple Assets



Often a dataset will inlcude prices for multiple assets. If you are analyzing just a single asset, you can simply filter the dataset prior to adding on the necessary indicators. However, if you are building a portfolio and need to add indicators to each asset, care must be taken. As an example, extra steps need to be taken to calculate the moving averages correctly above, because you dont want to mix the records of the various assets when calculating the moving averages.

Splitting a Dataset:
Joining a Dataset:

Contents