Lean
$LEAN_TAG$
TimeSeriesForecast.cs
1
/*
2
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4
*
5
* Licensed under the Apache License, Version 2.0 (the "License");
6
* you may not use this file except in compliance with the License.
7
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8
*
9
* Unless required by applicable law or agreed to in writing, software
10
* distributed under the License is distributed on an "AS IS" BASIS,
11
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
* See the License for the specific language governing permissions and
13
* limitations under the License.
14
*/
15
16
using
System;
17
18
namespace
QuantConnect.Indicators
19
{
20
/// <summary>
21
/// Represents an indicator capable of predicting new values given previous data from a window.
22
/// Source: https://tulipindicators.org/tsf
23
/// </summary>
24
public
class
TimeSeriesForecast
:
WindowIndicator
<IndicatorDataPoint>,
IIndicatorWarmUpPeriodProvider
25
{
26
/// <summary>
27
/// Creates a new TimeSeriesForecast indicator with the specified period
28
/// </summary>
29
/// <param name="name">The name of this indicator</param>
30
/// <param name="period">The period over which to look back</param>
31
public
TimeSeriesForecast
(
string
name,
int
period)
32
: base(name, period)
33
{
34
if
(period < 2)
35
{
36
throw
new
ArgumentException(
Messages
.
RollingWindow
.
InvalidSize
, nameof(period));
37
}
38
}
39
40
/// <summary>
41
/// Creates a new TimeSeriesForecast indicator with the specified period
42
/// </summary>
43
/// <param name="period">The period over which to look back</param>
44
public
TimeSeriesForecast
(
int
period)
45
: this($
"TSF{period})"
, period)
46
{
47
}
48
49
/// <summary>
50
/// Computes the next value for this indicator from the given state.
51
/// </summary>
52
/// <param name="window">The window of data held in this indicator</param>
53
/// <param name="input">The input value to this indicator on this time step</param>
54
/// <returns>A new value for this indicator</returns>
55
protected
override
decimal
ComputeNextValue
(
IReadOnlyWindow<IndicatorDataPoint>
window,
IndicatorDataPoint
input)
56
{
57
if
(!
IsReady
)
58
{
59
return
0;
60
}
61
62
// calculations are derived from https://tulipindicators.org/tsf
63
decimal x1 = 0;
64
decimal x2 = 0;
65
decimal xy = 0;
66
decimal y = 0;
67
68
var i =
Period
- 1;
69
for
(; i > 0; i--)
70
{
71
x1 += i;
72
x2 += i * i;
73
xy += window[i].Value * (
Period
- i);
74
y += window[i].Value;
75
}
76
77
x1 +=
Period
;
78
x2 +=
Period
*
Period
;
79
80
xy += window[0].Value *
Period
;
81
y += window[0].Value;
82
83
var bd = 1 / (
Period
* x2 - x1 * x1);
84
var b = (
Period
* xy - x1 * y) * bd;
85
var a = (y - b * x1) * (1m /
Period
);
86
87
return
a + b * (
Period
+ 1);
88
}
89
}
90
}
Indicators
TimeSeriesForecast.cs
Generated by
1.8.17