Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
-17.845
Tracking Error
0.112
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
from datetime import datetime, timedelta
import json
import math



class ExuberAlgorithm(QCAlgorithm):

    def Initialize(self):

        # budgets for strategies
        self.budget = 100000                        # budget
        self.exuber_budget = self.budget / 2        # budget exuber
        self.exuber_agg_budget = self.budget / 2    # budget exuber aggregate
        self.confidence_threshold_exuber = 1        # thresgold for exuber strategy
        self.confidence_threshold_exuberagg = 3     # threshold for exuber agg strategy
        
        self.SetStartDate(2021, 5, 18)
        # self.SetEndDate(2020, 1, 5)
        self.SetCash(100000)
        self.symbol = self.AddData(Radf, "RADFDATA", Resolution.Minute).Symbol
        # self.symbol_radf_agg = self.AddData(RadfAgg, "RADFAGGDATA", Resolution.Minute).Symbol
        self.spy = self.AddEquity("SPY", Resolution.Minute).Symbol
        # self.spy = self.AddCrypto("BTCUSD", Resolution.Minute, Market.GDAX).Symbol
        # Radf.set_algo(self)
        
        # init
        self.exuber_size = 0
        self.exuber_agg_size = 0
        self.window_close = RollingWindow[float](2)
        
    def OnData(self, data):
        
        # close rolling window
        if not data.ContainsKey(self.spy):
            self.Log(f'Not data for SPY!')
            return
        spy_close = data[self.spy].Close
        self.Log(spy_close)
        # self.window_close.Add(spy_close)
        # if not self.window_close.IsReady:
        #     return

        # Check for exuber data
        if not data.ContainsKey(self.symbol):
            self.Log(f'Not ready')
            return
        self.Log(f'Data Received. Value: {data[self.symbol].Value}, adf: {data[self.symbol].GetProperty("adf")}, index time: {data[self.symbol].Time}')
        # self.Log(f'Data Received. Value: {data[self.symbol].Value}, adf: {data[self.symbol].GetProperty("adf")}, date_QC: {self.Time}, index time: {data[self.symbol].Time} algotime: {data[self.symbol].GetProperty("algotime")} datetry: {data[self.symbol].GetProperty("datetry")}')
        # Data Received. Value: -1.7466, adf: -1.7466, date: 20210525000000, date_QC: 2021-05-25 03:36:00.800171, index time: 2021-05-25 03:36:00 algotime: 20210525 073522 datetry: 20210525 073422
        
        # # exuber alpha
        # indicator_exuber = data[self.symbol].GetProperty("adf")
        # self.Plot("Indicators", "Inidacator Exuber", indicator_exuber)
        # self.Plot("Indicators", "Threshold", self.confidence_threshold_exuber)
        # if self.exuber_size == 0 and indicator_exuber < self.confidence_threshold_exuber:
        #     self.exuber_size = math.floor(self.exuber_budget / spy_close)
        #     self.buy_order = self.MarketOrder(self.spy, self.exuber_size)
        #     self.Log(f"Buy Exuber. Exuber size after buy {self.exuber_size}")
        # elif self.exuber_size > 0 and indicator_exuber > self.confidence_threshold_exuber:
        #     # current_return = self.window_close[0] - self.window_close[1]
        #     # if current_return < 0:
        #     self.sell_order = self.MarketOrder(self.spy, -self.exuber_size)
        #     self.last_pl = self.buy_order.AverageFillPrice - self.sell_order.AverageFillPrice
        #     self.exuber_budget = self.exuber_budget + self.last_pl
        #     self.exuber_size = 0
        #     self.Log("Sell Exuber")

        # # If radf agg data not readz cont
        # if not data.ContainsKey(self.symbol_radf_agg):
        #     self.Log(f'Radf agg not ready')
        #     return
        # self.Log(f'Data Received. Value: {data[self.symbol_radf_agg].Value}, adf: {data[self.symbol_radf_agg].GetProperty("adf")}, date: {data[self.symbol_radf_agg].GetProperty("date_")}, date_QC: {self.Time}')
        
        # # exuber alpha
        # indicator_exuber_agg = data[self.symbol_radf_agg].GetProperty("adf")
        # self.Plot("Indicators", "Inidacator Exuber Agg", indicator_exuber_agg)
        # self.Plot("Indicators", "Exuber Agg Threshold", self.confidence_threshold_exuberagg)
        # if self.exuber_agg_size == 0 and indicator_exuber_agg < self.confidence_threshold_exuberagg:
        #     self.exuber_agg_size = math.floor(self.exuber_agg_budget / spy_close)
        #     self.buy_order_agg = self.MarketOrder(self.spy, self.exuber_agg_size)
        #     self.Log("Buy ExubeeAgg")
        # elif self.exuber_agg_size > 0 and indicator_exuber_agg > self.confidence_threshold_exuberagg:
        #     self.sell_order_agg = self.MarketOrder(self.spy, -self.exuber_agg_size)
        #     self.last_pl = self.buy_order_agg.AverageFillPrice - self.sell_order_agg.AverageFillPrice
        #     self.exuber_agg_budget = self.exuber_agg_budget + self.last_pl
        #     self.exuber_agg_size = 0
        #     self.Log("Sell ExubeeAgg")


class Radf(PythonData):
    # algo = None
    
    # @staticmethod
    # def set_algo(algo):
    #     Radf.algo = algo
    # def ceil_dt(dt, delta):
    #     return dt + (datetime.min - dt) % delta
    
    def GetSource(self, config, date, isLive):
        if isLive:
            date_argument = date.strftime("%Y%m%d%H%M%S")
            source = "http://207.154.227.4/alphar/radf_point?symbols=SPY&date=" + date_argument + "&window=100&price_lag=1&use_log=1&time=minute"
            return SubscriptionDataSource(source, SubscriptionTransportMedium.RemoteFile)
        else:
            date_argument = date.strftime("%Y%m%d%H%M%S")
            source = "http://207.154.227.4/alphar/radf_point?symbols=SPY&date=" + date_argument + "&window=100&price_lag=1&use_log=1&time=minute"
            return SubscriptionDataSource(source, SubscriptionTransportMedium.RemoteFile)

    def Reader(self, config, line, date, isLive):
        index = Radf()
        index.Symbol = config.Symbol

        if isLive:
            # try:
            line = json.loads(line)[0]
            index.Time = datetime.now() - timedelta(minutes=1) 
            index.EndTime = datetime.now()

            # index.Time = datetime.strptime(line['datetime'], '%Y-%m-%d %H:%M:%S')   # 2021-05-25 03:35:00
            # index.Time = datetime.now()
            # index.Time = datetime.now() - timedelta(minutes=1) 
            # index.EndTime = datetime.now() 
            # index.SetProperty('algotime', datetime.now().strftime("%Y%m%d %H%M%S")) # 20210525 073522
            # datetry = datetime.now() - timedelta(minutes=1)
            # index.SetProperty('datetry', datetry.strftime("%Y%m%d %H%M%S"))         # 20210525 073222
            # datetry2 = self.ceil_dt(datetime.now(), timedelta(minutes=1))
            # index.SetProperty('datetry2', datetry2.strftime("%Y%m%d %H%M%S"))
            
            # Radf.algo.Log(f"Reader date {Radf.algo.Time} {index.Time}")
            index.Value = line['adf']  # Random value
            index.SetProperty('adf', line['adf'])

            return index
            # except ValueError:
            #     return None
        else:
            line = json.loads(line)[0]
            index.Time = datetime.strptime(line['datetime'], '%Y-%m-%d %H:%M:%S')
            # index.Time = datetime.now()
            # index.Time = datetime.now() - timedelta(minutes=1) 
            # index.EndTime = datetime.now() 
            
            # Radf.algo.Log(f"Reader date {Radf.algo.Time} {index.Time}")
            index.Value = line['adf']  # Random value
            index.SetProperty('adf', line['adf'])
            index.SetProperty('date_', str(date.strftime("%Y%m%d%H%M%S")))
            return index

        return index



# class RadfAgg(PythonData):
    
#     def GetSource(self, config, date, isLive):
#         if isLive:
#             date_argument = date.strftime("%Y%m%d%H%M%S")
#             source = "http://207.154.227.4/alphar/radf_point_sp?date=" + date_argument + "&window=100&price_lag=1&use_log=1&agg_type=std&number_of_assets=5"
#             return SubscriptionDataSource(source, SubscriptionTransportMedium.RemoteFile)
#         # else:
#         #     source = "https://www.dropbox.com/s/4d9wp4ojnd439zz/0-100-1.csv?dl=1"
#         # return SubscriptionDataSource(source, SubscriptionTransportMedium.RemoteFile)

#     def Reader(self, config, line, date, isLive):
#         index = Radf()
#         index.Symbol = config.Symbol

#         if isLive:
#             try:
#                 line = json.loads(line)[0]
#                 index.Time = datetime.now()
#                 index.Value = 1.0  # Random value
#                 index.SetProperty('adf', line['adf'])
#                 index.SetProperty('date_', str(date))
#                 index.SetProperty('date_', str(date.strftime("%Y%m%d%H%M%S")))
#             except ValueError:
#                 return None
#         else:
#             line = json.loads(line)[0]
#             index.Time = datetime.strptime(line['datetime'], '%Y-%m-%d %H:%M:%S')
#             index.Value = 1.0  # Random value
#             index.SetProperty('adf', line['adf'])
#             index.SetProperty('date_', str(date))
#             index.SetProperty('date_', str(date.strftime("%Y%m%d%H%M%S")))

#             # if not (line.strip() and line[0].isdigit()): return None

#             # data = line.split(',')
#             # index.Time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S') + timedelta(hours=1)
#             # index.Value = float(data[2])
#             # index.SetProperty('date_', datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S') + timedelta(hours=1))
#             # index.SetProperty('adf', float(data[1]))
#             # index.SetProperty('sadf', float(data[2]))

#         return index