I am writing an algorithm to count the number of bars have passed since the n-th peak.
Assuming that I have a list of integer which keeps track of all the occurrences of peak as below.
3,7,10,13The above tells me that the peak occurs at the index
3,7,10and13.
The length of the source data is15.
Let n = 1
then I should be seeing a resultant list as below:
-
index 0 = null– there is no peak yet -
index 1 = null– there is no peak yet -
index 2 = null– there is no peak yet -
index 3 = 0– peak was hit here so there bars passed is 0 -
index 4 = 1– peak was hit in previous bar so the bars passed is 1 -
index 5 = 2– peak was already hit and the number of bars passed is 2 -
index 6 = 3– peak was already hit and the number of bars passed is 3 -
index 7 = 0– peak hit here again so the number of bars passed since the last 1 (n) peak is 0 and result follows as below:index 8 = 1,
index 9 = 2,
index 10 = 0,
index 11 = 1,
index 12 = 2,
index 13 = 0,
index 14 = 1
Assume n = 2
number of bars passed since 2 most recent peaks. So the result is as below:
-
index 0 = null -
index 1 = null -
index 2 = null -
index 3 = null– first peak butn = 2so there is no 2nd peak so far… -
index 4 = null -
index 5 = null -
index 6 = null -
index 7 = 4– second peak only hit here, so the number of days passed since the last 2 peak is 4, this is counted from the index where the first peak was hit, in this case is 3 -
index 8 = 5 -
index 9 = 6 -
index 10 = 3– another peak hit here, the peak before this (n = 2) happened atindex = 7, so it is counted fromindex = 7 -
index 11 = 4 -
index 12 = 5 -
index 13 = 3– another peak hit here, the peak before this (n = 2) happened atindex = 10, so it is counted fromindex = 10 -
index 14 = 4
I wrote an algorithm to accomplish this however, it’s not giving me the right output. I would appreciate if someone could tell me what’s wrong with my algo or propose a better way doing this.
int nth = GetNValue();// Get the N Value...
//SourceData = listData
int peakCount = 0;
int value= 0;
int barssince = 0;
List<Data> listValue = new List<Data>();
List<int> listResult = new List<int); //to hold the result..
List<int> listPeaks = GetPeakValue();
for (int index = 0; index < listData.Count; index++)
{
if (peakcount > 0)
{
barssince++;
listValue[listValue.Count - 1].Value = barssince;
}
int foundPeak = listPeaks.Find(delegate(int p) { return p == index; });
if (foundPeak != -1)//Peak FOund
{
peakcount++;
listValue.Add(new Data() { Value = barssince });
if (peakcount > nth)
{
listValue.RemoveAt(0);
}
barssince = 0;
}
value = listValue.Count >= nth ? listValue.Sum(p => p.Value) : null;
listResult.Add(value);
}
private class Data
{
public int Value { get; set; }
}
Try this: