5

我有一系列股票报价,我想获取最后一小时的所有数据并对其进行一些处理。我正在尝试通过响应式扩展 2.0 来实现这一点。我在另一篇文章中阅读了使用间隔,但我认为已弃用。

4

4 回答 4

9

这种扩展方法会解决您的问题吗?

public static IObservable<T[]> RollingBuffer<T>(
    this IObservable<T> @this,
    TimeSpan buffering)
{
    return Observable.Create<T[]>(o =>
    {
        var list = new LinkedList<Timestamped<T>>();
        return @this.Timestamp().Subscribe(tx =>
        {
            list.AddLast(tx);
            while (list.First.Value.Timestamp < DateTime.Now.Subtract(buffering))
            {
                list.RemoveFirst();
            }
            o.OnNext(list.Select(tx2 => tx2.Value).ToArray());
        }, ex => o.OnError(ex), () => o.OnCompleted());
    });
}
于 2012-07-25T08:54:02.653 回答
4

您正在寻找窗口操作员!这是我写的关于使用重合序列(序列的重叠窗口) http://introtorx.com/Content/v1.0.10621.0/17_SequencesOfCoincidence.html的长篇文章

所以如果你想建立一个滚动平均值,你可以使用这种代码

var scheduler = new TestScheduler();
var notifications = new Recorded<Notification<double>>[30];
for (int i = 0; i < notifications.Length; i++)
{
  notifications[i] = new Recorded<Notification<double>>(i*1000000, Notification.CreateOnNext<double>(i));
}
//Push values into an observable sequence 0.1 seconds apart with values from 0 to 30
var source = scheduler.CreateHotObservable(notifications);

source.GroupJoin(
      source,   //Take values from myself
      _=>Observable.Return(0, scheduler), //Just the first value
      _=>Observable.Timer(TimeSpan.FromSeconds(1), scheduler),//Window period, change to 1hour
      (lhs, rhs)=>rhs.Sum())    //Aggregation you want to do.
    .Subscribe(i=>Console.WriteLine (i));
scheduler.Start();

我们可以看到它在接收值时输出滚动和。

0, 1, 3, 6, 10, 15, 21, 28...

于 2012-07-25T11:14:36.897 回答
1

很可能Buffer是您正在寻找的内容:

var hourlyBatch = ticks.Buffer(TimeSpan.FromHours(1));
于 2012-07-19T15:48:30.150 回答
1

或者假设数据已经被Timestamp编辑,只需使用Scan

    public static IObservable<IReadOnlyList<Timestamped<T>>> SlidingWindow<T>(this IObservable<Timestamped<T>> self, TimeSpan length)
    {
        return self.Scan(new LinkedList<Timestamped<T>>(),
                         (ll, newSample) =>
                         {
                             ll.AddLast(newSample);
                             var oldest = newSample.Timestamp - length;
                             while (ll.Count > 0 && list.First.Value.Timestamp < oldest)
                                 list.RemoveFirst();

                             return list;
                         }).Select(l => l.ToList().AsReadOnly());
    }
于 2015-06-29T21:52:09.987 回答