def _initialize(self, strategy=None, start=None, end=None, timezone=None, commission=None): self.start = start self.end = end self.commission = commission self.timezone=timezone self.portfolio = Portfolio(strategy, start, end, commission, self.frequency, self.refresh_rate, self.trigger_time) self.context = self.portfolio.context # 最小精度 self.context.min_order = {} for univ in self.universe: exchange = univ.split('.')[1] self.context.min_order[exchange] = {} # print(self.context.min_order) for univ in self.universe: exchange = univ.split('.')[1] symbol = univ.split('.')[0].lower() min_order_qty, min_order_amount = get_min_order(exchange, symbol) self.context.min_order[exchange][symbol] = {'min_order_qty':min_order_qty, 'min_order_amount':min_order_amount} # 记录universe所有的asset self.universe_assets = list() for univ in self.universe: base_asset = univ.split('.')[0].split('/')[0].lower() quote_asset = univ.split('.')[0].split('/')[1].lower() if base_asset not in self.universe_assets: self.universe_assets.append(base_asset) if quote_asset not in self.universe_assets: self.universe_assets.append(quote_asset) self.all_assets = list(set(AccountManager().asset_varieties + self.universe_assets)) # print(self.all_assets) # # 初始每个账户添加除初始化之外的universe的asset # for name,account in self.portfolio.accounts.items(): # for asset in universe_assets: # if asset not in account.current_position.keys(): # account.current_position[asset] = SpotPosition('spot', asset, 0, 0, 0, 0) self.total_dates = get_total_dates(self.frequency, 1, self.trigger_time, self.start, self.end) self.strategy_dates = get_total_dates(self.frequency, self.refresh_rate, self.trigger_time, self.start, self.end) if self.frequency in ['d','1d','day','1day']: self.day_date=get_day_dates(self.start, self.end,self.refresh_rate) else: self.day_date=get_day_dates(self.start, self.end) # 先输出report的dates信息,画图用 output({"display_type": "strategy", "dates":self.day_date}) try: self.initialize(self.context) except Exception: output({"display_type": "error", "error_msg": traceback.format_exc()}) return 1
'granularity':granularity #以秒为单位的时间间隔,1分钟取值60 1小时取值3600 一天取值86400 } #一次请求获得K线长度不超过300,可以多次反复请求 r = requests.get(url,params=payload) klines=json.loads(r.text) return klines if __name__=='__main__': exchange='coinbase' symbol='btcusd' freq='1d' start1='2017-01-01 00:00:00' end1='2020-05-31 00:00:00' start2=datetime.strptime(start1,'%Y-%m-%d %H:%M:%S').timestamp() end2=datetime.strptime(end1,'%Y-%m-%d %H:%M:%S').timestamp() length1=get_total_dates(freq,1,0,start1,end1) if freq == '1d': interval=86400 count=round((end2-start2)/(lenght1-1)) if count>1: for i in range(count) data1=kline_coinbase('2017-03-23T08:00:00.000Z','2017-12-23T08:00:00.000Z',86400) df=data1.sort_index(axis=0,by='date',ascending=True) years = dict() for i in range(len(df)): year = (datetime.strptime(df.iloc[i]['date'],'%Y-%m-%d %H:%M:%S')).year if year not in years: years[year] = list() tempdata1= (df.iloc[i][1:7].values)
def get_data(exchange, symbol, frequency, start_date, end_date, timezone): data = get_bars(symbol, exchange, frequency=frequency, start_date=start_date, end_date=end_date, timezone=timezone) df_data = pd.DataFrame(data) # total_ts = get_total_timestamps(start_date, end_date) #只能获得天的日期 total_ts = get_total_dates(frequency, 1, 0, start_date, end_date) #天或者分钟的日期, #对df_data清醒数据清洗 if len(df_data) > 1: if df_data['timestamp'][0] > 0 and df_data['close'][0] > 0: for x in range(1, len(df_data)): if df_data['close'][x] == 0: df_data.iloc[x, 1:6] = df_data.iloc[x - 1, 1:6] else: nonzero = df_data[df_data['close'] > 0].index.tolist() if len(nonzero) > 0: for n in range(0, nonzero[0]): df_data.iloc[n, 1:6] = df_data.iloc[nonzero[0], 1:6] for x in range(1, len(df_data)): if df_data['high'][x] == 0 and df_data['close'][x] == 0: df_data.iloc[x, 1:6] = df_data.iloc[x - 1, 1:6] if len(df_data) == len(total_ts): df_data['timestamp'] = total_ts else: print('data error in cleaning, please wait') df_date = np.array(df_data['timestamp'], dtype='uint64') ts_date = [] for i in range(0, len(total_ts)): temp1 = datetime.strptime(total_ts[i], '%Y-%m-%d %H:%M:%S').timestamp() ts_date.append(round(temp1)) #total_ts转化为时间戳形式 ts_date = np.array(ts_date, dtype='uint64') temp2 = np.zeros([len(ts_date), 5]) df_data1 = pd.DataFrame( temp2, index=range(len(ts_date)), columns=['open', 'high', 'low', 'close', 'volume']) df_data1.insert(0, 'timestamp', total_ts) #创建一个完整的dataframe,下面把df_data的值复制进去,再把没有的部分补上 if len(df_data) < len(total_ts): x = len(df_data) - 1 start1 = 0 while x > 0: if df_date[x] != ts_date[x]: x -= 1 elif df_date[x] == ts_date[x]: start1 = x break if start1 > 0: df_data1.iloc[0:start1, 1:6] = df_data.iloc[0:start1, 1:6] for j in range(start1, len(ts_date)): if ts_date[j] in df_date: loacte1 = np.argwhere(df_date == ts_date[j]) df_data1.iloc[j, 1:6] = df_data.iloc[int(loacte1[0]), 1:6] else: if j > 0: df_data1.iloc[j, 1:6] = df_data1.iloc[j - 1, 1:6] else: for j in range(0, len(ts_date)): if ts_date[j] in df_date: loacte1 = np.argwhere(df_date == ts_date[j]) df_data1.iloc[j, 1:6] = df_data.iloc[int(loacte1[0]), 1:6] else: if j > 0: df_data1.iloc[j, 1:6] = df_data1.iloc[j - 1, 1:6] if len(df_data) > len(total_ts): for j in range(0, len(ts_date)): if ts_date[j] in df_date: loacte1 = np.argwhere(df_date == ts_date[j]) df_data1.iloc[j, 1:6] = df_data.iloc[int(loacte1[0]), 1:6] else: if j > 0: df_data1.iloc[j, 1:6] = df_data1.iloc[j - 1, 1:6] df_data = df_data1 return df_data