C#计算时间序列的移动中位数SortedList< DateTime,double> - 提高绩效?
我有一个计算时间序列的移动中值的方法。像移动平均线一样,它使用固定的窗口或周期(有时称为回溯期)。
如果周期为10,它将创建前10个值(0-9)的数组,然后找到它们的中值。它将重复此操作,将窗口递增1步(现在值为1-10),依此类推......因此,此处的移动部分。这个过程与移动平均线完全相同。
中值可通过以下方式找到:
对数组的值进行排序
如果数组中有奇数个值,请取中间值。 5个值的排序数组的中值将是第3个值。
如果数组中存在偶数个值,请在中间的每一侧取两个值并取平均值。 6个值的排序数组的中值为(2nd + 3rd)/ 2。
我创建了一个函数,通过填充
List<double>
,调用List<>.Sort()
,然后找到合适的值来计算它。
计算它是正确的,但我很想知道是否有办法改善这种计算的性能。也许是通过手动滚动double[]
而不是使用列表。
我的实现如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Moving_Median_TimeSeries
{
class Program
{
static void Main(string[] args)
{
// created a a sample test time series of 10 days
DateTime Today = DateTime.Now;
var TimeSeries = new SortedList<DateTime, double>();
for (int i = 0; i < 10; i++)
TimeSeries.Add(Today.AddDays(i), i * 10);
// write out the time series
Console.WriteLine("Our time series contains...");
foreach (var item in TimeSeries)
Console.WriteLine(" {0}, {1}", item.Key.ToShortDateString(), item.Value);
// calculate an even period moving median
int period = 6;
var TimeSeries_MovingMedian = MovingMedian(TimeSeries, period);
// write out the result of the calculation
Console.WriteLine("nThe moving median time series of {0} periods contains...", period);
foreach (var item in TimeSeries_MovingMedian)
Console.WriteLine(" {0}, {1}", item.Key.ToShortDateString(), item.Value);
// calculate an odd period moving median
int period2 = 5;
var TimeSeries_MovingMedian2 = MovingMedian(TimeSeries, period);
// write out the result of the calculation
Console.WriteLine("nThe moving median time series of {0} periods contains...", period2);
foreach (var item in TimeSeries_MovingMedian2)
Console.WriteLine(" {0}, {1}", item.Key.ToShortDateString(), item.Value);
}
public static SortedList<DateTime, double> MovingMedian(SortedList<DateTime, double> TimeSeries, int period)
{
var result = new SortedList<DateTime, double>();
for (int i = 0; i < TimeSeries.Count(); i++)
{
if (i >= period - 1)
{
// add all of the values used in the calc to a list...
var values = new List<double>();
for (int x = i; x > i - period; x--)
values.Add(TimeSeries.Values[x]);
// ... and then sort the list <- there might be a better way than this
values.Sort();
// If there is an even number of values in the array (example 10 values), take the two mid values
// and average them. i.e. 10 values = (5th value + 6th value) / 2.
double median;
if (period % 2 == 0) // is any even number
median = (values[(int)(period / 2)] + values[(int)(period / 2 - 1)]) / 2;
else // is an odd period
// Median equals the middle value of the sorted array, if there is an odd number of values in the array
median = values[(int)(period / 2 + 0.5)];
result.Add(TimeSeries.Keys[i], median);
}
}
return result;
}
}
}
没有找到相关结果
已邀请:
2 个回复
眠缝
屑凉赦