Overall Statistics
Total Trades
716
Average Win
0.64%
Average Loss
-0.65%
Compounding Annual Return
15.293%
Drawdown
11.800%
Expectancy
0.070
Net Profit
15.836%
Sharpe Ratio
0.746
Loss Rate
46%
Win Rate
54%
Profit-Loss Ratio
0.98
Alpha
0.122
Beta
0.066
Annual Standard Deviation
0.174
Annual Variance
0.03
Information Ratio
0.093
Tracking Error
0.213
Treynor Ratio
1.963
Total Fees
$338.12
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC, NuSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn import preprocessing
from collections import Counter


class TachyonOptimizedRegulators(QCAlgorithm):

    def Initialize(self):
        
        #user inputs
        #self.sl_perc = 0.015
        #self.tp_perc = 0.02
        
        self.lookback_window =100
        self.feature_window = 10
        
        self.fastsma_data = {}
        self.slowsma_data = {}
        fastmaperiod = 5
        slowmaperiod = 10
        
        self.SetBrokerageModel(BrokerageName.FxcmBrokerage)
        self.SetRiskManagement(MaximumDrawdownPercentPerSecurity(0.01))
        self.SetStartDate(2018, 4, 8)
        self.SetEndDate(2019,4,20)
        self.SetCash(10000)
        
        #Add forex data
        
        self.currency_list = ["AUDUSD","CHFJPY","EURAUD","EURCAD","EURCHF","EURGBP",
                                "EURJPY","EURNZD","EURUSD","GBPCHF","GBPJPY","GBPUSD",
                                "NZDUSD","USDCAD","USDCHF","USDJPY"]
        
        for currency in self.currency_list:
            self.symbolObj = self.AddForex(currency, Resolution.Daily, Market.FXCM)
            self.fastsma_data[currency] = self.SMA(currency, fastmaperiod)
            self.slowsma_data[currency] = self.SMA(currency, slowmaperiod)
            
            self.Log(self.symbolObj) 
            
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Monday), self.TimeRules.AfterMarketOpen("EURUSD", 30), self.rebalance)
        #self.Schedule.On(self.DateRules.EveryDay(DayOfWeek.Friday), self.TimeRules.BeforeMarketClose("EURUSD", 20), self.MomentumFilter)
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Friday), self.TimeRules.BeforeMarketClose("EURUSD", 30), self.closeall)
        
    def OnData(self, data):
        self.data = data
        self.Log(self.data)
        pass
    
    def MachineLearning(self):
        
        entry_rules = {}
        candle_raw = self.History(self.currency_list, self.lookback_window)                                   #change
        
        for currency in self.currency_list:
            
            prices = candle_raw.loc[currency]["close"]
            #print(prices)
            
            #Feature preparation
            start_bar = self.feature_window
            price_list = prices.tolist()
            
            X = []
            y = []
            
            bar = start_bar
            #Feature creation
            while bar < len(price_list)-1:
                try:
                    end_price = price_list[bar+1]
                    begin_price = price_list[bar]
                    
                    pricing_list = []
                    xx = 0
                    for _ in range(self.feature_window):
                        price = price_list[bar-(self.feature_window-xx)]
                        pricing_list.append(price)
                        xx += 1
                    features = np.around(np.diff(pricing_list)/pricing_list[:-1]*100.0, 1)
                    #features.reshape(-1, 1)
                    # print(features)
                    
                    #creating labels
                    if end_price > begin_price:
                        label = 1
                    else:
                        label = -1
                    
                    bar += 1
                    X.append(features)
                    y.append(label)
                    
                except Exception as e:
                    bar += 1
                    print(('feature creation', str(e)))
                    
            clf1 = RandomForestClassifier()
            clf2 = LinearSVC()
            clf3 = NuSVC()
            clf4 = LogisticRegression()
            
            last_prices = price_list[-self.feature_window:]
            current_features = np.around(np.diff(last_prices)/last_prices[:-1]*100.0, 1)
            
            X.append(current_features)
            X = preprocessing.scale(X)
            #X.reshape(-1, 1)
            
            current_features = X[-1]
            current_features.reshape(-1, 1)
            X = X[:-1]
            
            # print(X)
            # print(current_features)
            
            clf1.fit(X,y)
            clf2.fit(X,y)
            clf3.fit(X,y)
            clf4.fit(X,y)
            
            p1 = clf1.predict([current_features])[0]
            p2 = clf2.predict([current_features])[0]
            p3 = clf3.predict([current_features])[0]
            p4 = clf4.predict([current_features])[0]
            
            #Voting for Classifiers
            if Counter([p1,p2,p3,p4]).most_common(1)[0][1] >= 4:
                p = Counter([p1,p2,p3,p4]).most_common(1)[0][0]
            else:
                p = 0
            
            entry_rules[currency] = p
        
        return entry_rules
                
    def rebalance(self):
        
        ml = self.MachineLearning()
        
        buy_symbols = []
        sell_symbols = []
        
        for k,v in ml.items():
            if v==1:
                buy_symbols.append(k)
            elif v==-1:
                sell_symbols.append(k)
        
        new_symbols = buy_symbols + sell_symbols
        
        weights = 1.0/len(new_symbols)
            
        for i in buy_symbols:
            
            ma_fast = self.fastsma_data[i].Current.Value
            ma_slow = self.slowsma_data[i].Current.Value
            
            ma_buffer = abs((ma_fast - ma_slow)*100)
            
            #stop_price = self.Securities[i].Price
            #stop_price = float(self.fxdata[i].Close)
            
            if ma_buffer>=0.10:
                self.Log("Buy Signal Confirmed on  " + str(i) + "    Buying ....")
                self.SetHoldings(i, 1.0)
                #self.StopMarketOrder(i, -self.Portfolio[i].Quantity, stop_price*(1.00 - self.sl_perc))
                #self.LimitOrder(i, -self.Portfolio[i].Quantity, stop_price*(1.00 + self.tp_perc))
                self.Log("Buy Order Successful")
        
        for s in sell_symbols:
            
            ma_fast = self.fastsma_data[s].Current.Value
            ma_slow = self.slowsma_data[s].Current.Value
            
            ma_buffer = abs((ma_fast - ma_slow)*100)
            
            #stop_price = self.Securities[s].Price
            #stop_price = float(self.fxdata[s].Close)
            
            if ma_buffer>0.10:
                self.Log("Sell Signal Confirmed on  " + str(s) + "    Selling ....")
                self.SetHoldings(s, -1.0)
                #self.StopMarketOrder(s, self.Portfolio[s].Quantity, stop_price*(1.00 + self.sl_perc))
                #self.LimitOrder(s, self.Portfolio[s].Quantity, stop_price*(1.00 - self.tp_perc))
                self.Log("Sell Order Successful")
        
    
    def closeall(self):
        for s in self.currency_list:
            if self.Portfolio[s].Invested:
                self.Log("Closing All Open Trades: ITS FRIDAY YO, BEST DAY TO COUNT MONEY")
                self.Liquidate(s)
                self.Log("All Trades Closed Successfully " + "Now we count money -_-")