Search code examples
c#moving-averagepine-scripttradingview-apicomputational-finance

My C# Weighted Moving Average result is different than TradingView's, how does TradingView calculate WMA?


Finance charts on TradingView provide a weighted moving average (WMA) value based on a series of past stock prices.

I've written a C# method (shown below) to calculate these WMA values so they are exactly the same as the results on TradingView, given the same stock price data.

After testing my script, I believe I am calculating the WMA correctly, and have verified my results on another online WMA calculator.

My issue is that my results are slightly different than TradingView's results, usually differing at the third decimal place of precision on each WMA value.

To give you a real-life example, here's a set of 10 closing prices for Apple from April 1st, 2020:

  1. 3:00 PM - $241.30
  2. 2:59 PM - $241.01
  3. 2:58 PM - $241.04
  4. 2:57 PM - $241.01
  5. 2:56 PM - $241.00
  6. 2:55 PM - $241.15
  7. 2:54 PM - $241.47
  8. 2:53 PM - $241.35
  9. 2:52 PM - $241.61
  10. 2:51 PM - $241.57

They come into my script through a "Prices" object (which can contain more price values than actually are needed, thus the extra 'startIndex' & 'howManyPeriods' parameters):

 public static decimal WeightedMovingAverage(Prices prices, int startIndex = 0, decimal howManyPeriods = -1)
    {
        // Get the correct number of periods
        if (howManyPeriods < 1) howManyPeriods = prices.Count - startIndex;

        // Loop through calculations for the WMA
        decimal numerator = 0, denominator = 0;
        for (int i = 0; i < howManyPeriods; i++)
        {
            Price price = prices[i + startIndex];
            numerator += price.Value * (howManyPeriods - i);
            denominator += i + 1;
        }
        return numerator / denominator;
    }

In this example, these 10 values produce the WMA result 241.16272727.

TradingView's wma Pine function returns 241.16324727

That's a small difference of 0.00052 ...but this is a big problem for me because I use this result for other math operations and the difference becomes magnified and thus unusable.

I cannot find an explanation for the difference, and this has brought me to a grinding halt.

I doubt it's a rounding error in Pine since their user manual specifies:

The internal precision of floats in Pine is 1e-10

The only documentation I've found from TradingView or Pine on exactly how they calculate their WMA seems to match my script perfectly, so I'm out of ideas and am looking for help. Hopefully I'm just missing something obvious!

My best guess is that Pine has an alternative WMA equation, but I haven't been able to find it.

Any help or ideas would be greatly appreciated!


Solution

  • See the v4 refman for the calculation: https://www.tradingview.com/pine-script-reference/v4/#fun_wma