Survival/Include/Survival/SurvivalCore.mqh
ayantrader ayantrader 8e5f45bb2a Add standard errors, and correct two explanations flagged in review
CSurvival gains SurvivalSE (Greenwood), IncidenceSE and
ConditionalIncidenceSE (Aalen), and a free SurvProbCI that puts a
log-log interval around a probability so it cannot leave [0,1] on a
thin risk set. One IncidenceVar(from,to,cause) worker serves both the
unconditional and the conditional figures, since conditioning on
survival past a bar only re-bases the same increments.

TradeHistory: the comment on the unbounded HistorySelect gave the
wrong reason. A position whose only close falls after the cutoff is
censored correctly under a narrowed range; the case that actually
breaks is a position partially closed before the cutoff and fully
closed after, whose partial exit would be read as its final one.

SurvivalPanel: the refresh gate watched PositionsTotal() alone, which
misses every change that leaves the count intact - a partial close, a
netting reversal, a close and an open inside one bar, or a swap of
which position is described. LiveKey() folds the count together with
the tracked position's ticket, volume and open time.

SurvivalCore: ConditionalIncidence's header now states the
conditioning convention exactly rather than describing it as the
trades that reached the age.

SurvivalDemo: the iCustom note now states the input group behaviour
positively instead of contrasting it with the documentation.

README rewritten to match what the project became: competing risks
rather than cumulative hazard, the standard errors, and an honest
disclaimer about the demonstration Expert's result.
2026-09-24 00:29:26 +05:00
556 lines
21 KiB
MQL5
//+------------------------------------------------------------------+
//| SurvivalCore.mqh |
//| MMQ — Muhammad Minhas Qamar |
//| www.mql5.com/en/articles/23928 |
//+------------------------------------------------------------------+
#property copyright "MMQ — Muhammad Minhas Qamar"
#property link "https://www.mql5.com/en/articles/23928"
#property version "1.00"
#property strict
#include <Survival\SurvivalTypes.mqh>
//+------------------------------------------------------------------+
//| CSurvival - every curve this project needs, from one sweep. |
//| |
//| Durations are non-negative bar counts, so nothing is sorted. |
//| Each trade is bucketed by duration and the array walked once |
//| from bar zero, carrying the risk set. O(n + D), and short |
//| enough to check by eye against the textbook definition. |
//| |
//| S(t) all-cause Kaplan-Meier: the fraction of trades still |
//| running after t bars, whatever ends them. |
//| |
//| CIF Aalen-Johansen incidence, per cause. Each increment |
//| is weighted by S(t-), so a trade already removed by |
//| the other outcome cannot count as a future case. |
//| |
//| h(t) hazard: the share of the risk set that resolved at |
//| exactly t. This is the aging profile - whether trades |
//| get more or less likely to resolve as they get older. |
//| |
//| naive the same question answered wrongly, by Kaplan-Meier |
//| on wins alone with losses called censored. Kept |
//| because the gap between it and the CIF is the point. |
//| |
//| Curves go into dense per-bar arrays, so a lookup is an index |
//| rather than a search and the panel's conditionals cost nothing. |
//+------------------------------------------------------------------+
class CSurvival
{
private:
int m_count; // trades fitted
int m_dmax; // longest duration seen, in bars
int m_n_win; // terminal wins
int m_n_loss; // terminal losses
int m_n_cens; // still open at the cutoff
//--- step functions evaluated at every bar in [0, m_dmax]
double m_surv[];
double m_cif_win[];
double m_cif_loss[];
double m_naive_win[];
int m_at_risk[];
//--- event counts per bar, kept so the hazard needs no second pass
int m_d_win[];
int m_d_loss[];
void Reset(void);
//--- events of one cause at one bar, and the Aalen variance of the
//--- incidence accumulated over a bar range.
int EventsAt(const int bar,const int cause) const;
double IncidenceVar(const int from,const int to,
const int cause) const;
public:
CSurvival(void) { Reset(); }
//--- Bucket, sweep, and fill every curve. Returns false only on
//--- structurally impossible input: an empty sample, a negative
//--- duration, or one longer than SURV_MAX_DURATION.
bool Fit(const SurvObservation &obs[],const int count);
//--- sample composition, worth printing next to any curve because
//--- a curve fitted on nine trades looks exactly like one fitted
//--- on nine hundred.
int Count(void) const { return m_count; }
int MaxDuration(void) const { return m_dmax; }
int Wins(void) const { return m_n_win; }
int Losses(void) const { return m_n_loss; }
int Censored(void) const { return m_n_cens; }
//--- step-function lookups. Bars past the end of the sample return
//--- the last known value, which is the correct reading of a
//--- Kaplan-Meier curve beyond its final observation.
double SurvivalAt(const int bar) const;
double IncidenceAt(const int bar,const int cause) const;
double NaiveIncidenceAt(const int bar) const;
int AtRiskAt(const int bar) const;
double HazardAt(const int bar,const int cause) const;
//--- smallest bar whose all-cause survival has fallen to 'q' or
//--- below; -1 when the curve never gets there. Median is q=0.5.
int QuantileDuration(const double q) const;
int MedianDuration(void) const { return QuantileDuration(0.5); }
//--- Last bar whose risk set still holds at least 'min_n' trades.
//--- Every survival curve degenerates in its tail, where one or two
//--- observations decide the estimate, so a figure meant to be read
//--- as evidence should be read at or before this bar.
int ReliableBar(const int min_n) const;
//--- P(cause occurs in bars bar+1 .. bar+horizon | the trade
//--- survived bar 'bar'), the quantity only survival analysis gives.
double ConditionalIncidence(const int bar,const int horizon,
const int cause) const;
//--- Standard errors for the three figures above. Nothing in the
//--- estimator needs them; a reader quoting a figure does.
double SurvivalSE(const int bar) const;
double IncidenceSE(const int bar,const int cause) const;
double ConditionalIncidenceSE(const int bar,const int horizon,
const int cause) const;
};
//+------------------------------------------------------------------+
//| Return to the pre-Fit state so a single instance can be reused. |
//+------------------------------------------------------------------+
void CSurvival::Reset(void)
{
m_count =0;
m_dmax =0;
m_n_win =0;
m_n_loss=0;
m_n_cens=0;
ArrayFree(m_surv);
ArrayFree(m_cif_win);
ArrayFree(m_cif_loss);
ArrayFree(m_naive_win);
ArrayFree(m_at_risk);
ArrayFree(m_d_win);
ArrayFree(m_d_loss);
}
//+------------------------------------------------------------------+
//| Bucket the sample by duration, then sweep once from bar zero. |
//| |
//| The risk set n is maintained as "trades whose duration is at |
//| least t". It is read before the events at t are applied and |
//| decremented after, which encodes the standard tie convention: |
//| a trade censored at exactly t was still under observation at |
//| t and leaves immediately afterwards. Getting that backwards |
//| shifts every curve by one bar in the wrong direction. |
//+------------------------------------------------------------------+
bool CSurvival::Fit(const SurvObservation &obs[],const int count)
{
Reset();
if(count<=0 || count>ArraySize(obs))
return(false);
//--- pass one: validate and find the span the buckets must cover.
int dmax=0;
for(int i=0;i<count;i++)
{
const int d=obs[i].duration;
if(d<0 || d>SURV_MAX_DURATION)
return(false);
if(d>dmax)
dmax=d;
}
int b_cens[];
if(ArrayResize(m_d_win,dmax+1)<0 || ArrayResize(m_d_loss,dmax+1)<0 ||
ArrayResize(b_cens,dmax+1)<0)
{
Reset();
return(false);
}
ArrayInitialize(m_d_win,0);
ArrayInitialize(m_d_loss,0);
ArrayInitialize(b_cens,0);
//--- pass two: drop every trade into the bucket for its duration.
for(int i=0;i<count;i++)
{
const int d=obs[i].duration;
switch(obs[i].outcome)
{
case SURV_OUTCOME_WIN:
m_d_win[d]++;
m_n_win++;
break;
case SURV_OUTCOME_LOSS:
m_d_loss[d]++;
m_n_loss++;
break;
default:
b_cens[d]++;
m_n_cens++;
}
}
m_count=count;
m_dmax =dmax;
if(ArrayResize(m_surv,dmax+1)<0 || ArrayResize(m_cif_win,dmax+1)<0 ||
ArrayResize(m_cif_loss,dmax+1)<0 || ArrayResize(m_naive_win,dmax+1)<0 ||
ArrayResize(m_at_risk,dmax+1)<0)
{
//--- m_count>0 is what every lookup reads as "curves ready",
//--- so a failed allocation must not leave it set.
Reset();
return(false);
}
//--- pass three: the sweep. Everything below is one traversal of
//--- the bucket array carrying five running quantities.
int n_risk =count; // trades with duration >= t
double surv =1.0; // all-cause S(t)
double surv_win =1.0; // wins-only KM, the naive curve
double cif_win =0.0; // Aalen-Johansen, wins
double cif_loss =0.0; // Aalen-Johansen, losses
for(int t=0;t<=dmax;t++)
{
m_at_risk[t]=n_risk;
const int d_win =m_d_win[t];
const int d_loss=m_d_loss[t];
const int d_all =d_win+d_loss;
if(d_all>0 && n_risk>0)
{
const double n =(double)n_risk;
const double s_prev=surv;
//--- the two increments that make this Aalen-Johansen and
//--- not two independent Kaplan-Meiers: each is scaled by
//--- the probability of still being in contention at all.
cif_win += s_prev*(double)d_win /n;
cif_loss += s_prev*(double)d_loss/n;
surv *= 1.0-(double)d_all/n;
surv_win *= 1.0-(double)d_win/n;
}
m_surv[t] =surv;
m_cif_win[t] =cif_win;
m_cif_loss[t] =cif_loss;
m_naive_win[t]=1.0-surv_win;
n_risk -= d_win+d_loss+b_cens[t];
}
return(true);
}
//+------------------------------------------------------------------+
//| S(bar). Before the first bar nothing has happened yet, so the |
//| curve is still at one; past the last it holds its final value. |
//+------------------------------------------------------------------+
double CSurvival::SurvivalAt(const int bar) const
{
if(m_count<=0 || bar<0)
return(1.0);
return(m_surv[bar>m_dmax ? m_dmax : bar]);
}
//+------------------------------------------------------------------+
//| Cumulative incidence of one cause by 'bar', or of both pooled. |
//+------------------------------------------------------------------+
double CSurvival::IncidenceAt(const int bar,const int cause) const
{
if(m_count<=0 || bar<0)
return(0.0);
const int b=(bar>m_dmax ? m_dmax : bar);
if(cause==SURV_CAUSE_WIN)
return(m_cif_win[b]);
if(cause==SURV_CAUSE_LOSS)
return(m_cif_loss[b]);
return(m_cif_win[b]+m_cif_loss[b]);
}
//+------------------------------------------------------------------+
//| The same question answered by treating losses as censored. Kept |
//| only so the two can be printed side by side. |
//+------------------------------------------------------------------+
double CSurvival::NaiveIncidenceAt(const int bar) const
{
if(m_count<=0 || bar<0)
return(0.0);
return(m_naive_win[bar>m_dmax ? m_dmax : bar]);
}
//+------------------------------------------------------------------+
//| How many trades were still under observation at this bar. |
//+------------------------------------------------------------------+
int CSurvival::AtRiskAt(const int bar) const
{
if(m_count<=0 || bar<0)
return(m_count);
if(bar>m_dmax)
return(0);
return(m_at_risk[bar]);
}
//+------------------------------------------------------------------+
//| Hazard at one bar: of the trades that reached it, the share |
//| that resolved there. Read across bars this is the aging |
//| profile, and it is the raw material every curve above is built |
//| from rather than a separate estimate. |
//+------------------------------------------------------------------+
double CSurvival::HazardAt(const int bar,const int cause) const
{
if(m_count<=0 || bar<0 || bar>m_dmax)
return(0.0);
const int n=m_at_risk[bar];
if(n<=0)
return(0.0);
int d=0;
if(cause==SURV_CAUSE_WIN)
d=m_d_win[bar];
else
if(cause==SURV_CAUSE_LOSS)
d=m_d_loss[bar];
else
d=m_d_win[bar]+m_d_loss[bar];
return((double)d/(double)n);
}
//+------------------------------------------------------------------+
//| First bar at which the all-cause curve has fallen to q or below. |
//| |
//| On an unfitted instance m_dmax is 0 but m_surv is empty, so |
//| without the guard the loop indexes a freed array. |
//+------------------------------------------------------------------+
int CSurvival::QuantileDuration(const double q) const
{
if(m_count<=0)
return(-1);
for(int t=0;t<=m_dmax;t++)
if(m_surv[t]<=q)
return(t);
return(-1);
}
//+------------------------------------------------------------------+
//| Last bar whose risk set is still worth quoting a figure from. |
//| |
//| The risk set is non-increasing, so this is a plain scan for the |
//| point where it drops through min_n. Returns -1 when even bar |
//| zero has fewer trades than that, which is the honest answer |
//| for a sample too small to read anywhere. |
//+------------------------------------------------------------------+
int CSurvival::ReliableBar(const int min_n) const
{
if(m_count<=0)
return(-1);
int last=-1;
for(int t=0;t<=m_dmax;t++)
{
if(m_at_risk[t]<min_n)
break;
last=t;
}
return(last);
}
//+------------------------------------------------------------------+
//| Forward incidence, conditioned on having survived this far. |
//| |
//| Dividing by S(bar) re-bases the increment on the trades that |
//| survived bar 'bar' rather than on every trade ever opened, so |
//| the window it reports on is bars bar+1 to bar+horizon and a |
//| trade resolving on bar 'bar' itself is in neither end of it. |
//+------------------------------------------------------------------+
double CSurvival::ConditionalIncidence(const int bar,const int horizon,
const int cause) const
{
if(m_count<=0 || horizon<=0 || bar<0)
return(0.0);
const double s=SurvivalAt(bar);
if(s<=0.0)
return(0.0);
const double lo=IncidenceAt(bar,cause);
const double hi=IncidenceAt(bar+horizon,cause);
const double p =(hi-lo)/s;
if(p<0.0)
return(0.0);
return(p>1.0 ? 1.0 : p);
}
//+------------------------------------------------------------------+
//| Events of one cause landing exactly on this bar, or of both. |
//+------------------------------------------------------------------+
int CSurvival::EventsAt(const int bar,const int cause) const
{
if(cause==SURV_CAUSE_WIN)
return(m_d_win[bar]);
if(cause==SURV_CAUSE_LOSS)
return(m_d_loss[bar]);
return(m_d_win[bar]+m_d_loss[bar]);
}
//+------------------------------------------------------------------+
//| Greenwood standard error of S(bar). |
//| |
//| A bar that removes the whole risk set contributes an undefined |
//| term and is skipped, the usual convention at the last event. |
//+------------------------------------------------------------------+
double CSurvival::SurvivalSE(const int bar) const
{
if(m_count<=0 || bar<0)
return(0.0);
const int hi=(bar>m_dmax ? m_dmax : bar);
double sum=0.0;
for(int t=0;t<=hi;t++)
{
const int n=m_at_risk[t];
const int d=m_d_win[t]+m_d_loss[t];
if(d<=0 || n<=d)
continue;
sum += (double)d/((double)n*(double)(n-d));
}
return(m_surv[hi]*MathSqrt(sum));
}
//+------------------------------------------------------------------+
//| Aalen variance of the incidence gained over [from, to], given |
//| survival past from-1. |
//| |
//| Three terms: the variance of the survival weight, the binomial |
//| variance of the cause-specific jumps, and the covariance of |
//| the two. Conditioning only re-bases the same increments, so |
//| from=0 gives the plain cumulative incidence and from=bar+1 |
//| the conditional figure, out of one routine. |
//+------------------------------------------------------------------+
double CSurvival::IncidenceVar(const int from,const int to,
const int cause) const
{
if(m_count<=0 || from<0 || to<from)
return(0.0);
const int hi=(to>m_dmax ? m_dmax : to);
if(from>hi)
return(0.0);
const double base=SurvivalAt(from-1);
if(base<=0.0)
return(0.0);
//--- pass one: the total the deviations below are measured against.
double f_end=0.0;
for(int t=from;t<=hi;t++)
{
const int n=m_at_risk[t];
if(n<=0)
continue;
f_end += (SurvivalAt(t-1)/base)*(double)EventsAt(t,cause)/(double)n;
}
//--- pass two: accumulate the three terms.
double f=0.0,v_surv=0.0,v_jump=0.0,cov=0.0;
for(int t=from;t<=hi;t++)
{
const int n=m_at_risk[t];
if(n<=0)
continue;
const int d_all=m_d_win[t]+m_d_loss[t];
const int d_k =EventsAt(t,cause);
const double s_pre=SurvivalAt(t-1)/base;
f += s_pre*(double)d_k/(double)n;
const double gap=f_end-f;
if(d_all>0 && n>d_all)
v_surv += gap*gap*(double)d_all/((double)n*(double)(n-d_all));
if(d_k>0)
{
v_jump += s_pre*s_pre*(double)(n-d_k)*(double)d_k
/((double)n*(double)n*(double)n);
cov += gap*s_pre*(double)d_k/((double)n*(double)n);
}
}
const double v=v_surv+v_jump-2.0*cov;
return(v>0.0 ? v : 0.0);
}
//+------------------------------------------------------------------+
//| Aalen standard error of IncidenceAt(bar, cause). |
//+------------------------------------------------------------------+
double CSurvival::IncidenceSE(const int bar,const int cause) const
{
if(m_count<=0 || bar<0)
return(0.0);
return(MathSqrt(IncidenceVar(0,bar,cause)));
}
//+------------------------------------------------------------------+
//| Aalen standard error of ConditionalIncidence, taken over the |
//| same window that function reports on. |
//+------------------------------------------------------------------+
double CSurvival::ConditionalIncidenceSE(const int bar,const int horizon,
const int cause) const
{
if(m_count<=0 || horizon<=0 || bar<0)
return(0.0);
return(MathSqrt(IncidenceVar(bar+1,bar+horizon,cause)));
}
//+------------------------------------------------------------------+
//| Log-log interval around a probability estimate. |
//| |
//| A Wald interval runs outside [0,1] on the small risk sets |
//| these curves are usually read on; this one cannot. Returns |
//| false on a degenerate estimate, leaving lo and hi at p. |
//+------------------------------------------------------------------+
bool SurvProbCI(const double p,const double se,const double z,
double &lo,double &hi)
{
lo=p;
hi=p;
if(p<=0.0 || p>=1.0 || se<=0.0 || z<=0.0)
return(false);
const double t=z*se/(p*MathLog(p));
const double a=MathPow(p,MathExp(t));
const double b=MathPow(p,MathExp(-t));
lo=(a<b ? a : b);
hi=(a<b ? b : a);
if(lo<0.0)
lo=0.0;
if(hi>1.0)
hi=1.0;
return(true);
}
//+------------------------------------------------------------------+
//| Copy the observations belonging to one group into 'dst'. |
//| Returns how many were taken. |
//+------------------------------------------------------------------+
int SurvFilterByGroup(const SurvObservation &src[],const int count,
const long group,SurvObservation &dst[])
{
ArrayFree(dst);
const int cap=(count<ArraySize(src) ? count : ArraySize(src));
if(cap<=0)
return(0);
if(ArrayResize(dst,cap)<0)
return(0);
int n=0;
for(int i=0;i<cap;i++)
{
if(src[i].group!=group)
continue;
dst[n]=src[i];
n++;
}
ArrayResize(dst,n);
return(n);
}
//+------------------------------------------------------------------+