The Moving Average Trader

Overview


Calculating Indicators


moving average api


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

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

prices = $list(prices).merge(data=>ma.movingAverage(data.map(p=>p.close), 3),'ma').items;
					
Try it!

Calculating Trades


The following function, then takes a price object calculated above, and returns a portfolio of holdings based on holding the asset if its price is above its moving average, otherwise going to cash.


let trader = async function(price, nav){
  if(price.ma !== null && price.ma>price.close) return {IBM:nav/price.close};
  else return {cash:nav}
}
					
Try it!