I'm just curious if this could be done in a single LINQ statement. I need to do a simple weighted average like this:
IEnumerable<double> values = { v0, v1, v2, v3, ...}
WeightedAverage = (((v0 + v1) / 2 + v2) / 2 + v3) / 2 ...
In LINQ, you can find the average of the given sequence by using the Average method. This method returns the average of the elements present in the given sequence or collection. It returns nullable, non-nullable decimal, double, floats, int, etc. values.
The simple average of a set of observations is computed as the sum of the individual observations divided by the number of observations in the set.
In order to calculate your weighted average price per share, simply multiply each purchase price by the amount of shares purchased at that price, add them together, and then divide by the total number of shares.
Calculate a Weighted Average in Pandas Using NumpyThe numpy library has a function, average() , which allows us to pass in an optional argument to specify weights of values. The function will take an array into the argument a= , and another array for weights under the argument weights= .
double average = values.Aggregate((x, y) => (x + y) / 2.0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With