根据先前的数据创建与函数相关的新项
本文关键字:函数 新项 数据 创建 | 更新日期: 2023-09-27 18:01:58
List<History> data = new List<History>(){
new History() {Symbol="a", Close = 1.0m, Date = new DateTime(2016, 2, 1) },
new History() {Symbol="a", Close = 1.2m, Date = new DateTime(2016, 2, 2) },
new History() {Symbol="a", Close = 1.3m, Date = new DateTime(2016, 2, 3) },
new History() {Symbol="b", Close = 1.2m, Date = new DateTime(2016, 2, 1) },
new History() {Symbol="b", Close = 1.2m, Date = new DateTime(2016, 2, 2) },
new History() {Symbol="b", Close = 1.3m, Date = new DateTime(2016, 2, 3) },
};
var StockGroupList = data
.GroupBy(o => o.Symbol)
.OrderBy(o => o.Key)
.ToList();
我想创建一个像
这样的新列表select new { Symbol, Close, Date, Vol};
其中Vol
为两天标准差,Symbol="a"
在2016, 2, 3
时的Vol
为2016, 2, 3
和2016, 2, 2
时close
的函数。此外,第一天的Vol
(例如2016, 2, 1
)默认为Vol = 0
。
List<dynamic> NewData = new List<dynamic>
{
new { Symbol = "a", Close = 1.0m, Date = new DateTime(2016, 2, 1), Vol = 0 },
new { Symbol = "a", Close = 1.0m, Date = new DateTime(2016, 2, 2), Vol = SD(Close of 2016, 2, 1, Close of 2016, 2, 2) },
new { Symbol = "a", Close = 1.0m, Date = new DateTime(2016, 2, 3), Vol = SD(Close of 2016, 2, 2, Close of 2016, 2, 3) },
......
};
可以把SD(x,y)
看作一个给定的函数,简称为SD(x,y) = x+y
。另外,如果SD
的参数是一个List
,比如List[Close of 2016, 2, 2, Close of 2016, 2, 3)]
,那我该怎么办呢?
如果SD
遵循
decimal OneStdDev = (decimal)(new DescriptiveStatistics(data.Select(o => (double)o.Close)).StandardDeviation);
我该怎么办?
我怀疑你在这种情况下需要分组,如果我理解你的问题,你想计算当前和以前的历史记录之间的SD
。
您可以使用Linq
扩展方法来完成此操作。
var results = data
.Take(1)
.Select(x=>new {x.Symbol, x.Close, x.Date, Vol = 0.0m})
.Concat(data.Zip(data.Skip(1), (first,second) =>
new
{
second.Symbol,
second.Close,
second.Date,
Vol = first.Close + second.Close // Use whatever logic you want.
}
));
输出:Symbol =a, Close=1.0, Date=2/1/2016 12:00:00 AM, Vol = 0.0
Symbol =a, Close=1.2, Date=2/2/2016 12:00:00 AM, Vol = 2.2
Symbol =a, Close=1.3, Date=2/3/2016 12:00:00 AM, Vol = 2.5
Symbol =b, Close=1.2, Date=2/1/2016 12:00:00 AM, Vol = 2.5
Symbol =b, Close=1.2, Date=2/2/2016 12:00:00 AM, Vol = 2.4
Symbol =b, Close=1.3, Date=2/3/2016 12:00:00 AM, Vol = 2.5
检查Demo