Search Framework:
TimeSeries
Namespace: WealthLab.Core
Parent: TimeSeriesBase
Descendants: IndicatorBase

The TimeSeries class manages a series of numeric double values keyed to a list of DateTimes. The two primary properties of TimeSeries are:

  • Values - a list of double values
  • DateTimes - a list of DateTime values These two lists are synchronized, so a value and DateTime at the same index represent the same point in the series. When accessing values, you can use the TimeSeries default indexer rather than explicitly accessing Values. For example:
//assume ts is an instance of a TimeSeries
double n1 = ts.Values[10];
double n2 = ts[10];

These two statements are functionally equivalent. public void WriteToBinaryFile(string fileName)

Writes the DateTimes and Values of the TimeSeries to a WealthLab binary TimeSeries file.
The resulting file can be loaded using **ReadFromBinaryFile**.
TimeSeries overloads many C# operators so calculations and comparisons can be performed directly on complete series.
Arithmetic operations return a new TimeSeries containing the result for each bar. Comparison and logical operations return TimeSeries values that can be used as Boolean series in subsequent calculations.
Constructors
TimeSeries
public TimeSeries()
public TimeSeries(List<DateTime> dateTimes, bool fillNaN = true)
public TimeSeries(List<DateTime> dateTimes, double fillValue)

The parameterless constructor creates a TimeSeries that manages its own DateTimes. When adding values to this instance, use an Add method that supplies both a value and DateTime. The second constructor associates the TimeSeries with an existing List of DateTimes. By default, its Values are initialized to Double.NaN. Pass false for fillNaN if you intend to populate the values yourself. The third constructor associates the TimeSeries with an existing List of DateTimes and initializes every value to fillValue.



Inherited Members

Members
Abs
public TimeSeries Abs()

Returns a new TimeSeries containing the absolute value of each value in the source TimeSeries.


AnnualizedReturn
public double AnnualizedReturn

Returns the annualized percentage return of the TimeSeries, based on its TotalReturnPct and the amount of time represented by the series.


Cache
public ConcurrentDictionary<string, object> Cache

A generic cache Dictionary that can be used to store objects associated with the TimeSeries. Indicators can use the Cache to store related calculated objects and avoid performing the same calculations repeatedly.


Clone
public TimeSeries Clone()

Returns a new TimeSeries containing copies of the DateTimes and Values in the source TimeSeries.


ConsecBarsAbove
public TimeSeries ConsecBarsAbove(TimeSeries ts2)
public TimeSeries ConsecBarsAbove(double value)

Returns a new TimeSeries containing the number of consecutive bars that the source TimeSeries has remained above another TimeSeries or a constant value. The count resets to zero whenever the source value is equal to or below the comparison value. Double.NaN values also reset the count.


ConsecBarsBelow
public TimeSeries ConsecBarsBelow(TimeSeries ts2)
public TimeSeries ConsecBarsBelow(double value)

Returns a new TimeSeries containing the number of consecutive bars that the source TimeSeries has remained below another TimeSeries or a constant value. The count resets to zero whenever the source value is equal to or above the comparison value. Double.NaN values also reset the count.


Covariance
public double Covariance(TimeSeries other)

Returns the covariance between this TimeSeries and other. The two TimeSeries must contain the same number of values. Returns Double.NaN if they do not have the same Count or there is insufficient data.


CrossesOver
public bool CrossesOver(double value, int idx)
public bool CrossesOver(TimeSeries ts, int idx)

Returns true if the TimeSeries crosses over a constant value or another TimeSeries at idx. For a crossover to occur, the source must be above the comparison value at idx and must previously have been below it. Bars where the two values are equal do not prevent detection of the crossover. When comparing two TimeSeries, they must contain the same number of values.


CrossesUnder
public bool CrossesUnder(double value, int idx)
public bool CrossesUnder(TimeSeries ts, int idx)

Returns true if the TimeSeries crosses under a constant value or another TimeSeries at idx. For a crossunder to occur, the source must be below the comparison value at idx and must previously have been above it. When comparing two TimeSeries, they must contain the same number of values.


CrossOver
public TimeSeries CrossOver(TimeSeries ts)

Returns a new TimeSeries containing 1 at each point where the source TimeSeries crosses over ts, and 0 otherwise. The two TimeSeries must contain the same number of values.


CrossUnder
public TimeSeries CrossUnder(TimeSeries ts)

Returns a new TimeSeries containing 1 at each point where the source TimeSeries crosses under ts, and 0 otherwise. The two TimeSeries must contain the same number of values.


DateTimes
public override List<DateTime> DateTimes

Contains the DateTime corresponding to each value in the TimeSeries. Assigning a new DateTimes List causes the Values of the TimeSeries to be initialized to Double.NaN.


Description
public virtual string Description

Contains a text description of the TimeSeries. Indicators typically set this automatically. When plotting a plain TimeSeries from Strategy code, WealthLab can use the supplied plot name as its Description.


FillNaN
public void FillNaN()

Fills all values in the TimeSeries with Double.NaN.


FirstValidIndex
public int FirstValidIndex

Returns the first index containing valid data rather than Double.NaN. Indicators commonly contain Double.NaN in their initial values until enough source data is available to perform their calculation. You can also assign FirstValidIndex. If the assigned index does not actually contain valid data, WealthLab determines the first valid index from the series.


GetHighest
public double GetHighest(int bar, int range)

Returns the highest value in the TimeSeries looking backward from bar for up to range values. Returns Double.NaN if bar is outside the TimeSeries.


GetHighestBar
public int GetHighestBar(int bar, int range)

Returns the index at which the highest value was found when looking backward from bar for up to range values. Returns -1 if a valid result cannot be obtained.


GetLowest
public double GetLowest(int bar, int range)

Returns the lowest value in the TimeSeries looking backward from bar for up to range values. Returns Double.NaN if bar is outside the TimeSeries.


GetLowestBar
public int GetLowestBar(int bar, int range)

Returns the index at which the lowest value was found when looking backward from bar for up to range values. Returns -1 if a valid result cannot be obtained.


HighestBars
public TimeSeries HighestBars(int range)

Returns a new TimeSeries whose values contain the bar indexes at which the highest value over the specified range occurred.


LowestBars
public TimeSeries LowestBars(int range)

Returns a new TimeSeries whose values contain the bar indexes at which the lowest value over the specified range occurred.


MassageColors
public bool MassageColors

Determines whether WealthLab should adjust the plotted color of the TimeSeries to improve contrast with the currently selected Light or Dark Theme. New TimeSeries instances initialize this value using the current IndicatorFactory setting.


MaxDrawDown
public double MaxDrawDown

Returns the maximum drawdown, expressed as an absolute value, that occurred in the TimeSeries.


MaxDrawDownDate
public DateTime MaxDrawDownDate

Returns the DateTime on which MaxDrawDown occurred.


MaxDrawDownPct
public double MaxDrawDownPct

Returns the maximum percentage drawdown that occurred in the TimeSeries.


MaxDrawDownPctDate
public DateTime MaxDrawDownPctDate

Returns the DateTime on which MaxDrawDownPct occurred.


Parse
public static TimeSeries Parse(string s)

Creates and returns a TimeSeries from a string previously generated by Persist.


Persist
public string Persist()

Returns a string representation containing the TimeSeries' DateTimes and Values. The resulting string can subsequently be restored using Parse.


PopulateException
public bool PopulateException

Indicates that an exception occurred while the TimeSeries was being populated. WealthLab uses this property internally to prevent indicators that encountered population errors from being plotted.


ReadFromBinaryFile
public void ReadFromBinaryFile(
string fileName,
DateTime? startDate = null,
DateTime? endDate = null,
int maxBars = 0)

Populates the TimeSeries with data from a binary file created by WriteToBinaryFile. You can optionally restrict the data using startDate, endDate, or maxBars.


ReadFromFile
public void ReadFromFile(
string fileName,
DateTime? startDate = null,
DateTime? endDate = null,
int maxBars = 0,
string dateTimeFormat = "yyyyMMddHHmmss",
char separator = ',',
bool exactMatchOnly = false,
int skipLines = 0)

Populates the TimeSeries with data from a text file. By default, the method reads the format produced by WriteToFile. You can also read external files containing DateTime and numeric value pairs by specifying the appropriate dateTimeFormat and separator. Numeric values are parsed using invariant culture, so a period (.) is used as the decimal separator. The optional startDate, endDate, and maxBars parameters can restrict the amount of data loaded. skipLines can be used when reading external files containing header lines.


ReturnNDays
public double ReturnNDays(int idx, int days)

Returns the percentage change between the value at idx and the value corresponding to approximately days calendar days earlier. Returns Double.NaN if the requested index or earlier DateTime cannot be located.


ReturnYTD
public TimeSeries ReturnYTD()

Returns a new TimeSeries containing the year-to-date percentage change relative to the final value of the previous calendar year.


SeriesBarColors
public DateSynchedList<WLColor> SeriesBarColors

Contains optional bar-specific colors associated with the TimeSeries.


StreamingValue
public double StreamingValue

Contains the value associated with the current partial streaming bar. The default value is Double.NaN.


Sum
public TimeSeries Sum()
public TimeSeries Sum(int period)

The parameterless version returns a new TimeSeries containing the cumulative sum of the source TimeSeries. The period version returns a new TimeSeries containing the rolling sum of the source values over the specified number of bars.


TotalReturn
public double TotalReturn

Returns the difference between the final and first values of the TimeSeries. Returns zero if the TimeSeries contains fewer than two values.


TotalReturnPct
public double TotalReturnPct

Returns the total return of the TimeSeries as a percentage of its first value. Returns zero if the TimeSeries contains fewer than two values.


TurnsDown
public bool TurnsDown(int idx)

Returns true when the TimeSeries turns downward at idx. The method considers intervening equal values, so a series that rises, remains flat for one or more bars, and then declines is considered to have turned down.


TurnsUp
public bool TurnsUp(int idx)

Returns true when the TimeSeries turns upward at idx. The method considers intervening equal values, so a series that declines, remains flat for one or more bars, and then rises is considered to have turned up.


Variance
public double Variance()

Returns the sample variance of the valid values in the TimeSeries.

Example Code
### WriteToBinaryFile

WriteToFile
public void WriteToFile(string fileName)

Writes the DateTimes and Values of the TimeSeries to a text file. Each record contains the DateTime in yyyyMMddHHmmss format followed by the numeric value. Values are written using invariant culture. The resulting file can be loaded using ReadFromFile.



Operators
Comparison Operators
public static TimeSeries operator >(TimeSeries s1, TimeSeries s2)
public static TimeSeries operator >(TimeSeries s, double value)
public static TimeSeries operator >(double value, TimeSeries s)
public static TimeSeries operator <(TimeSeries s1, TimeSeries s2)
public static TimeSeries operator <(TimeSeries s, double value)
public static TimeSeries operator <(double value, TimeSeries s)
public static TimeSeries operator >=(TimeSeries s1, TimeSeries s2)
public static TimeSeries operator >=(TimeSeries s, double value)
public static TimeSeries operator >=(double value, TimeSeries s)
public static TimeSeries operator <=(TimeSeries s1, TimeSeries s2)
public static TimeSeries operator <=(TimeSeries s, double value)
public static TimeSeries operator <=(double value, TimeSeries s)

Compare the TimeSeries values to another TimeSeries or constant value and return a new TimeSeries representing the Boolean result. These Boolean TimeSeries can be combined with logical operators or passed to methods such as BarsSince and BooleanTest.


Logical Operators
public static TimeSeries operator &(TimeSeries s1, TimeSeries s2)
public static TimeSeries operator |(TimeSeries s1, TimeSeries s2)

Combine Boolean TimeSeries using logical AND or OR operations. For example:

Example Code
TimeSeries aboveBoth =
    bars.Close > SMA.Series(bars.Close, 200) &
    bars.Close > SMA.Series(bars.Close, 50);

operator-
public static TimeSeries operator -(TimeSeries s1, TimeSeries s2)
public static TimeSeries operator -(TimeSeries s, double value)
public static TimeSeries operator -(double value, TimeSeries s)

Performs subtraction between two TimeSeries instances or between a TimeSeries and a constant value.


operator*
public static TimeSeries operator *(TimeSeries s1, TimeSeries s2)
public static TimeSeries operator *(TimeSeries s, double value)
public static TimeSeries operator *(double value, TimeSeries s)

Performs multiplication between two TimeSeries instances or between a TimeSeries and a constant value.


operator/
public static TimeSeries operator /(TimeSeries s1, TimeSeries s2)
public static TimeSeries operator /(TimeSeries s, double value)
public static TimeSeries operator /(double value, TimeSeries s)

Performs division between two TimeSeries instances or between a TimeSeries and a constant value. When division by zero occurs, the corresponding result is zero.


operator+
public static TimeSeries operator +(TimeSeries s1, TimeSeries s2)
public static TimeSeries operator +(TimeSeries s, double value)
public static TimeSeries operator +(double value, TimeSeries s)

Performs addition between two TimeSeries instances or between a TimeSeries and a constant value.


operator>>
public static TimeSeries operator >>(TimeSeries ser, int period)

Returns a new TimeSeries shifted to the right by period bars. This effectively delays the information in the TimeSeries, making the shifted series safe for use in backtesting. For example, when shifting a series one bar to the right, the value at index X comes from index X-1 of the original series.



Static Methods
BarsSince
public static TimeSeries BarsSince(TimeSeries s)

Returns a new TimeSeries containing the number of bars since the most recent positive value in s. This is particularly useful with TimeSeries generated by WealthLab's comparison operators.


BooleanTest
public static TimeSeries BooleanTest(
TimeSeries s,
TimeSeries resultTrue,
TimeSeries resultFalse)

Returns a new TimeSeries whose value is taken from resultTrue when the corresponding value in s is greater than zero, and from resultFalse otherwise.


Log
public static TimeSeries Log(TimeSeries s)

Returns a new TimeSeries containing the natural logarithm of each value in s.


Max
public static TimeSeries Max(TimeSeries s, int period)

Returns a new TimeSeries containing the highest value in s over the specified rolling period.


Min
public static TimeSeries Min(TimeSeries s, int period)

Returns a new TimeSeries containing the lowest value in s over the specified rolling period.


Pow
public static TimeSeries Pow(TimeSeries s, double power)

Returns a new TimeSeries containing each value in s raised to the specified power.


Round
public static TimeSeries Round(TimeSeries s)

Returns a new TimeSeries containing the values in s rounded using Math.Round.


Sqrt
public static TimeSeries Sqrt(TimeSeries s)

Returns a new TimeSeries containing the square root of each valid, non-zero value in s.


Sum
public static TimeSeries Sum(TimeSeries s, int length)

Returns a new TimeSeries containing the rolling sum of s over the specified length. This is equivalent to calling:

Example Code
s.Sum(length);


Statistical Methods
Kurtosis
public TimeSeries Kurtosis(int period)

Returns a new TimeSeries containing the kurtosis of the source TimeSeries over the specified period. Kurtosis describes characteristics of the distribution of values, particularly the weight of its tails relative to a normal distribution.


MedianAbsoluteDeviation
public TimeSeries MedianAbsoluteDeviation(int period)

Returns a new TimeSeries containing the median absolute deviation over the specified period. Median absolute deviation is a robust measure of variability that is less affected by extreme values than standard deviation.


PercentRank
public TimeSeries PercentRank(int period)

Returns a new TimeSeries containing the percent rank of each value relative to the values within the specified period.


Skewness
public TimeSeries Skewness(int period)

Returns a new TimeSeries containing the skewness of the source TimeSeries over the specified period. Skewness measures the asymmetry of the distribution of values.