On Sat, 12 May 2007 02:49:56 -0700,
Ro********@yahoo.co.uk
<Ro********@yahoo.co.ukwrote:
Hi, What is the best way to use an array to find moving averages. [...]
In answer to the basic question, I would say that two good solutions would
be to either use the Queue<generic class, or implement a circular buffer
yourself with an array. Using the Queue<class involves a little more
overhead "behind the scenes", but allows your own code to most closely
match what it is you're actually doing. A circular buffer is slightly
more efficient, but the implementation in your own code would be less
direct.
Now, that said, your question has a bunch of other pieces of information
that may or may not be relevant to those of us trying to answer it. If
that information is relevant, IMHO you should do a better job of
explaining why. The information about the length of the moving average
(15 and 41 days) seems useful, but I'm left having no idea why you say "my
array will need to contain 12 columns", nor do I know why you say "the row
size will need to be a minimum of 50 rows". These statements may well be
correct, but we don't have enough context from you to understand why.
As an example of what I mentioned above, here are a couple of
implementations of a moving average you might consider using as an outline
for your own needs:
// Circular buffer
void MovingAverage(double[] pricesHistory, int cdayAverage)
{
double priceSum, priceMovingAverage;
double[] pricesMoving = new double[cdayAverage];
int ipriceCur, ipriceCircle, cpriceAveraged;
ipriceCur = 0;
ipriceCircle = 0;
cpriceAveraged = 0;
while (ipriceCur < pricesHistory.Length)
{
double priceCur = pricesHistory[ipriceCur];
priceSum += priceCur;
if (cpriceAveraged < pricesMoving.Length)
{
cpriceAveraged++;
}
else
{
ipriceCircle = ipriceCircle % pricesMoving.Length;
priceSum -= pricesMoving[ipriceCircle];
}
pricesMoving[ipriceCircle++] = priceCur;
priceMovingAverage = priceSum / cpriceAveraged;
}
}
// Queue
void MovingAverage(double[] pricesHistory, int cdayAverage)
{
double priceSum, priceMovingAverage;
Queue<doublepricesMoving = new Queue<double>(cdayAverage)
int ipriceCur;
ipriceCur = 0;
while (ipriceCur < pricesHistory.Length)
{
double priceCur = pricesHistory[ipriceCur];
priceSum += priceCur;
if (!(pricesMoving.Count < cdayAverage))
{
priceSum -= pricesMoving.Dequeue();
}
pricesMoving.Enqueue(priceCur);
priceMovingAverage = priceSum / pricesMoving.Count;
}
}
In either algorithm, the input data is passed in with "pricesHistory", the
number of days to average is pased in with "cdayAverage", and the
"priceMovingAverage" variable contains, at the end of each loop, the
current moving average given the input data.
Hope that helps.
Pete