0

I want to use the following method but as hobbyist programmer I cannot understand how to fill(format?) the SortedList that will be used as input to the method. I have a sql table with DateTime and a Value that will have always "close" string associated (see code)

looked at several answers but no conclusions at all

public static void AddBollingerBands(ref SortedList<DateTime, Dictionary<string, double>> data, int period, int factor)
{
    double total_average = 0;
    double total_squares = 0;

    for (int i = 0; i < data.Count(); i++)
    {
        total_average += data.Values[i]["close"];
        total_squares += Math.Pow(data.Values[i]["close"], 2);

        if (i >= period - 1)
        {
            double total_bollinger = 0;
            double average = total_average / period;

            double stdev = Math.Sqrt((total_squares - Math.Pow(total_average,2)/period) / period);
            data.Values[i]["bollinger_average"] = average;
            data.Values[i]["bollinger_top"] = average + factor * stdev;
            data.Values[i]["bollinger_bottom"] = average - factor * stdev;
.......
......

1 Answers1

0

Using .Values is a get operation only. The result is not a reference to the element in your sorted list, but instead an immutable var.

Ignoring the issues with not using SortedList properly, you can only change the value of a sortedList if you reference the element directly via its key:

data[keyValue]["total_bollinger"] = average;

The above line of code would update that value in the list accordingly.

Rather than iterate over the list via data.Count(), I would recommend iterating over the keys like this:

            var keys = data.Keys;
            foreach(var key in data.Keys)
            {
                double total_bollinger = 0;
                double average = total_average / period;

                double stdev = Math.Sqrt((total_squares - Math.Pow(total_average, 2) / period) / period);
                data[key]["total_bollinger"] = total_average;
            }
Erik Overflow
  • 2,220
  • 1
  • 5
  • 16
  • I have chosen this Bollinger Bands method from other I got after googling because has few code lines. This is the link https://stackoverflow.com/questions/14635735/how-to-efficiently-calculate-a-moving-standard-deviation and I assumed that was ok because I did not see any refutation. From your comments I understand that I must look for a better method (class?) to calculate the Bollinger values. – Luis Novais Reis Sep 10 '19 at 16:00