I would tell you the logic, you try and let us know.
The logic is, you create a flag in script for each monthend date and one for yearend date.
Now when you are trying to show data say month wise balances then use that flag to show data as on that day only. and same for year end.
The problem is that at script level, I dont know when it's a month end.
Cause on the original data, I may not have the balance value for the end of month on the day that the month ends.
For instance, on January 2012, the month ends on 31th of January of course. But I may not have data values for that particular day.
So the other answer, from Mr Wassenaar, is more practical due to the firstsortedvalue function that "flows" over data in other to pick the correct value within the month (or year).
But I understood what you said. Many times I create new fields during data load. I call those fields "derivated" fields and also use a standard suffix name for them, like "_DER" (from DERivated field).
Thanks anyway !