Overall Statistics
Total Trades
4405
Average Win
0.00%
Average Loss
0.00%
Compounding Annual Return
3.013%
Drawdown
0.500%
Expectancy
0.319
Net Profit
1.030%
Sharpe Ratio
1.777
Loss Rate
41%
Win Rate
59%
Profit-Loss Ratio
1.23
Alpha
0.026
Beta
0.049
Annual Standard Deviation
0.013
Annual Variance
0
Information Ratio
1.33
Tracking Error
0.047
Treynor Ratio
0.484
Total Fees
$0.00
import io, requests
import numpy as np
import pandas as pd
from datetime import datetime
from datetime import timedelta

feat_assets = ['AUDUSD', 'EURUSD', 'GBPUSD', 'NZDUSD', 'USDCAD', 'USDCHF', 'USDJPY', 'USDNOK', 'USDSEK', 'USDSGD']
trade_assets = ['EURAUD', 'EURNZD', 'GBPAUD', 'GBPNZD', 'AUDUSD', 'NZDUSD']
No_Channels = 10
Input_Size = 256

class BasicTemplateAlgorithm(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2019,1,3)  #Set Start Date
        self.SetEndDate(2019,5,8)    #Set End Date
        self.SetCash(100000)           #Set Strategy Cash
        self.SetBrokerageModel(BrokerageName.OandaBrokerage)
        for asset in list(set(feat_assets+trade_assets)): self.AddForex(asset, Resolution.Hour, Market.Oanda, True, 1.0)
        self.History(512, Resolution.Hour)
        self.SetBenchmark("EURUSD")
    def OnData(self, data):
        #if self.Time.hour % 4 != 0: return
        cc = None
        for asset in feat_assets:
            df = self.History([asset], timedelta(14), Resolution.Hour).loc[asset]
            df = df['bidclose'].resample('1H').interpolate(method='cubic')
            if asset[-3:] != 'USD': df = 1.0 / df
            df = np.log((df/df.shift(1)).tail(Input_Size))
            cc = df if cc is None else pd.concat([cc, df], axis=1)

        X = np.swapaxes(cc.values, 0, 1)
        
        sss = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        for i, asset in enumerate(trade_assets):
            sss[i] = self.Securities[asset].AskPrice / self.Securities[asset].BidPrice - 1.0
            
        self.Debug(sss)

        data = {'arr': X.reshape(-1).tolist(), 'spr': sss}
        response = requests.post('https://rota.serveo.net/test', json=data)
        try:
            weights = np.array(response.json()['arr'])
        except:
            self.Debug('JSONDecodeError')
            return

        '''
        values = []
        for asset in trade_assets:
            values.append(self.Portfolio[asset].Quantity * self.Securities[asset].Price)
        values = np.array(values)
        values /= np.sum(np.abs(values))
        self.Debug(values)
        '''
        self.Debug(weights)

        for i, asset in enumerate(trade_assets):
            #self.SetHoldings(asset, weights[i])
            self.Transactions.CancelOpenOrders(asset)

        cc = None
        for asset in trade_assets:
            df = self.History([asset], timedelta(14), Resolution.Hour).loc[asset]
            df = df['bidclose'].resample('1H').interpolate(method='cubic')
            df = np.log((df/df.shift(1)).tail(Input_Size))
            cc = df if cc is None else pd.concat([cc, df], axis=1)
        stdarr = np.exp(cc.abs().quantile(0.5).values)#0.25
            
        for i, asset in enumerate(trade_assets):
            oq = self.CalculateOrderQuantity(asset, weights[i])
            #oq -= self.Portfolio[asset].Quantity
            lp = self.Securities[asset].AskPrice * stdarr[i]
            if oq > 0: lp = self.Securities[asset].BidPrice / stdarr[i]
            if oq != 0: self.LimitOrder(asset, oq, lp)