Overall Statistics
Total Orders
11
Average Win
5.25%
Average Loss
-5.14%
Compounding Annual Return
-3.650%
Drawdown
23.700%
Expectancy
-0.326
Start Equity
100000.00
End Equity
78769.10
Net Profit
-21.231%
Sharpe Ratio
-0.421
Sortino Ratio
-0.548
Probabilistic Sharpe Ratio
0.003%
Loss Rate
67%
Win Rate
33%
Profit-Loss Ratio
1.02
Alpha
-0.038
Beta
-0.273
Annual Standard Deviation
0.074
Annual Variance
0.005
Information Ratio
-0.053
Tracking Error
0.121
Treynor Ratio
0.114
Total Fees
$0.00
Estimated Strategy Capacity
$460000.00
Lowest Capacity Asset
EURUSD 8G
Portfolio Turnover
0.73%
#region imports
from AlgorithmImports import *

from scipy import sparse
from scipy.sparse.linalg import spsolve
#endregion


class TrendFollowingAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2011,1,1)
        self.set_end_date(2017,5,30)
        self.set_cash(100000)
        self._numdays = 360*5  # set the length of training period
        self._syl = self.add_forex("EURUSD", Resolution.DAILY).symbol
        self._n,self.m = 2, 1
        self._trend = None
        self.set_benchmark(self._syl)
        history = self.history(self._numdays,Resolution.DAILY)
        self._close = [slice[self._syl].close for slice in history]
		
    def _hpfilter(self,X, lamb=1600):	
        X = np.asarray(X, float)
        if X.ndim > 1:
            X = X.squeeze()
        nobs = len(X)
        I = sparse.eye(nobs,nobs)
        offsets = np.array([0,1,2])
        data = np.repeat([[1.],[-2.],[1.]], nobs, axis=1)
        K = sparse.dia_matrix((data, offsets), shape=(nobs-2,nobs))
        use_umfpack = True
        self._trend = spsolve(I+lamb*K.T.dot(K), X, use_umfpack=use_umfpack)
	
    def on_data(self,data):
        self._close.append(self.portfolio[self._syl].price)
        self._hpfilter(self._close[-self._numdays:len(self._close)+1], 100)
        m_a_rules_today = (np.mean(self._trend[-self.m : len(self._trend)]) - np.mean(self._trend[-self._n : len(self._trend)]))
        m_a_rules_yesterday = (np.mean(self._trend[-self.m-1: len(self._trend)-1]) - np.mean(self._trend[-self._n-1 : len(self._trend)-1]))
        holdings = self.portfolio[self._syl].quantity
        
        if m_a_rules_today > 0 and m_a_rules_yesterday < 0:
        	  self.set_holdings(self._syl, 1)
        elif m_a_rules_today < 0 and m_a_rules_yesterday > 0:
            self.set_holdings(self._syl, -1)