Search code examples
xmlxslt-2.0

Simple Moving Average in XSLT


Is there way how to calculate a Simple Moving Average in XSLT 2.0? For example I will have a XML document where will be 100 values, but some function (SMA) after XSLT gives me just 50 values as output.

Thanks for all your ideas

EDIT

I added some example, as you can see I have XML document, where I have for every month a price of brand samsung. Now I would like to have just 2 values for price (for 5th month and 10th month as you can see on the picture below).

Same principle like here http://www.dummies.com/personal-finance/investing/stocks-trading/how-to-calculate-simple-moving-average-in-trading

Here is some XML document

<?xml version="1.0" encoding="UTF-8"?>
<trade>
    <phone month="1" brand="samsung">
        <price>1000</price>
    </phone>
    <phone month="2" brand="samsung">
        <price>890</price>
    </phone>
    <phone month="3" brand="samsung">
        <price>870</price>
    </phone>
    <phone month="4" brand="samsung">
        <price>950</price>
    </phone>
    <phone month="5" brand="samsung">
        <price>920</price>
    </phone>
    <phone month="6" brand="samsung">
        <price>930</price>
    </phone>
    <phone month="7" brand="samsung">
        <price>870</price>
    </phone>
    <phone month="8" brand="samsung">
        <price>830</price>
    </phone>
    <phone month="9" brand="samsung">
        <price>910</price>
    </phone>
    <phone month="10" brand="samsung">
        <price>950</price>
    </phone>
</trade>

Here is wanted result

Brand samsung
month  price
  5      avg(price[1] to price[9])
 10      avg(price[2] to price[10])  

SMA with 5 period


Solution

  • I did it by recursion http://xsltfiddle.liberty-development.net/6qVRKvN/1. It works fine, the result is like in the link in question. But one more thing did not work and it is if samples do not sorted by default by date. So if samples are randomly sorted, the result is not correct. How to sort the samples by date and then use the SMA?