General Topics
Technical Topics
Brokerage Firms
Community Lounge
Site Support

Java help - simple moving average

Discussion in 'Trading Software' started by elit, Oct 5, 2006.

1. elit

How do I code a 30 day simple moving average in java?

Like this?

X = (C + P[i to c-1] / i

X = Current MA
C = Current Price
P = P1, P2, P3 and so on
i = number of days in MA = 30

2. dcraig

I think this is correct. There are other ways.

double [] x; // your input time series

Code:
```int bars = 20;
double [] ma = new double [x.length - bars];  //
int k = 0;

for (int i = bars - 1; i < double.length; i++)
{
ma [k] = 0.0;
for (int j = 0; j < bars; j++)
{
ma [k] += x [i - j];
}
ma [k++] /= bars;
}
```

3. newbie2006

I really don't understand the above.

Isn't the simple moving average the summation of all the prices during the number of days divided by the number of days ?

5. newbie2006

dcraig,
I got what you mean, you are calculating the moving average for each bar as in backtesting, I thought he was talking about calculating it in real time, sorry my mistake

ET IS FREE BECAUSE OF THE FINANCIAL SUPPORT FROM THESE COMPANIES: