예제 #1
0
        /// <summary>
        /// Generate the annual returns plot using the python libraries.
        /// </summary>
        public override string Render()
        {
            var backtestReturns = ResultsUtil.EquityPoints(_backtest);
            var liveReturns     = ResultsUtil.EquityPoints(_live);

            var backtestTime     = backtestReturns.Keys.ToList();
            var backtestStrategy = backtestReturns.Values.ToList();

            var liveTime     = liveReturns.Keys.ToList();
            var liveStrategy = liveReturns.Values.ToList();

            var base64 = "";

            using (Py.GIL())
            {
                var backtestList = new PyList();
                var liveList     = new PyList();

                // We need to set the datetime index first before we resample
                //var backtestSeries = Pandas.Series(backtestStrategy.ToPython());
                var backtestSeries = new Series <DateTime, double>(backtestTime, backtestStrategy);

                // Get the annual returns for the strategy
                // ResampleEquivalence works similarly to Pandas' DataFrame.resample(...) method
                // Here we transform the series to resample to the year's start, then we get the aggregate return from the year.
                // Pandas equivalent:
                //
                // df.pct_change().resample('AS').sum().mul(100)
                var backtestAnnualReturns = backtestSeries.PercentChange().ResampleEquivalence(date => new DateTime(date.Year, 1, 1), agg => agg.Sum() * 100);

                // We need to set the datetime index first before we resample
                var liveSeries = new Series <DateTime, double>(liveTime, liveStrategy);

                // Get the annual returns for the live strategy.
                // Same as above, this is equivalent to:
                //
                // df.pct_change().resample('AS').sum().mul(100)
                var liveAnnualReturns = liveSeries.PercentChange().ResampleEquivalence(date => new DateTime(date.Year, 1, 1), agg => agg.Sum() * 100);

                // Select only the year number and pass it to the plotting library
                backtestList.Append(backtestAnnualReturns.Keys.Select(x => x.Year).ToList().ToPython());
                backtestList.Append(backtestAnnualReturns.Values.ToList().ToPython());
                liveList.Append(liveAnnualReturns.Keys.Select(x => x.Year).ToList().ToPython());
                liveList.Append(liveAnnualReturns.Values.ToList().ToPython());

                base64 = Charting.GetAnnualReturns(backtestList, liveList);
            }

            return(base64);
        }