def multi_line_view(self, df, b_date, cd_set_a, cd_set_b=[], size=(15, 7), make_file=False): cds_a = common.str_list(cd_set_a) cds_b = common.str_list(cd_set_b) fig, ax1 = plt.subplots(figsize=size) x = df.loc[b_date:].index plt.autoscale(True, axis='both') i = 1 for c in cds_a: if i == 1: ax1.plot(x, df.loc[b_date:, c], color='C' + str(i), lw=3, label=c) pass else: ax1.plot(x, df.loc[b_date:, c], color='C' + str(i), label=c) i += 1 if cds_b: ax2 = ax1.twinx() i = 6 for c in cds_b: ax2.plot(x, df.loc[b_date:, c], color='C' + str(i), label=c, alpha=0.7) ax1.plot(np.nan, color='C' + str(i), label=c) i += 1 x_length = len(x) jump = int(x_length / 10) xs = list() for i in range(10): xs.append(x[jump * i]) xs.append(x[-1]) ax1.set_xticks(np.arange(0, x_length + jump, jump)) ax1.set_xticklabels(xs, rotation=45) ax2.set_xticks(np.arange(0, x_length + jump, jump)) ax2.set_xticklabels(xs, rotation=45) ax1.legend(loc=0) if make_file: plt.savefig('./image/' + Visualize.today + cds_a[0] + ' multi_line_view.png', bbox_inches='tight')
def futures_basis_view(self, df, threshold, s_cd, make_file=False, size=(15, 7)): cds = common.str_list(s_cd) fig, ax = plt.subplots(figsize=size) x = df.index plt.fill_between(x, df[cds[0]], df[cds[0]] + df['basis'], facecolor='sienna', alpha=0.2) plt.plot(x, df[cds[0]], 'sienna', linestyle='--') plt.plot(x, df[cds[1]], 'C1', lw=3) x_length = len(x) jump = int(x_length / 10) xs = list() for i in range(10): xs.append(x[jump * i]) xs.append(x[-1]) plt.xticks(np.arange(0, x_length + jump, jump), xs, rotation=45) plt.legend() if make_file: plt.savefig('./image/' + VisualizeIntraday.today + cds[0] + ' futures_basis_view.png', bbox_inches='tight')
def position_view(self, df, s_cd, size=(15, 1), make_file=False): cds = common.str_list(s_cd) fig, ax = plt.subplots(figsize=size) x = df.index for c in cds: df['ps' + c] = 0 df.loc[df['p ' + c] == 'll', ['ps' + c]] = 1 df.loc[df['p ' + c] == 'sl', ['ps' + c]] = 1 df.loc[df['p ' + c] == 'zl', ['ps' + c]] = 1 df.loc[df['p ' + c] == 'ls', ['ps' + c]] = -1 df.loc[df['p ' + c] == 'ss', ['ps' + c]] = -1 df.loc[df['p ' + c] == 'zs', ['ps' + c]] = -1 plt.fill_between(x, df['ps' + c], 0, label=c) plt.yticks([-1, 0, 1], ["Short", "Zero", "Long"]) x_length = len(x) jump = int(x_length / 10) xs = list() for i in range(10): xs.append(x[jump * i]) xs.append(x[-1]) plt.xticks(np.arange(0, x_length + jump, jump), xs, rotation=45) plt.legend() if make_file: plt.savefig('./image/' + VisualizeIntraday.today + cds[0] + ' position_view.png', bbox_inches='tight')
def index_view(self, df, b_date, s_cd, size=(10, 7), make_file=False): fig, ax = plt.subplots(1, 1, figsize=size) x = df.loc[b_date:].index plt.autoscale(True, axis='both') cds = common.str_list(s_cd) for c in cds: plt.plot(x, df.loc[b_date:, c] / df.loc[b_date, c] * 100, label=c) x_length = len(x) jump = int(x_length / 10) xs = list() for i in range(10): xs.append(x[jump * i]) xs.append(x[-1]) plt.xticks(np.arange(0, x_length + jump, jump), xs, rotation=45) plt.legend() if make_file: plt.savefig('./image/' + Visualize.today + s_cd[0] + ' index_view.png', bbox_inches='tight')
def position_view_bar(self, df, cd, size=(15, 1), make_file=False): cds = common.str_list(cd) fig, ax = plt.subplots(figsize=size) x = df.index x_ticks = self.time_serial(df) plt.xticks(x_ticks[0], x_ticks[1]) plt.autoscale(True, axis='x') for c in cds: df['ps' + c] = 0 df.loc[df['p ' + c] == 'll', ['ps' + c]] = 1 df.loc[df['p ' + c] == 'sl', ['ps' + c]] = 1 df.loc[df['p ' + c] == 'zl', ['ps' + c]] = 1 df.loc[df['p ' + c] == 'ls', ['ps' + c]] = -1 df.loc[df['p ' + c] == 'ss', ['ps' + c]] = -1 df.loc[df['p ' + c] == 'zs', ['ps' + c]] = -1 plt.bar(range(x.size), df['ps' + c], width=1, label=c) plt.yticks([-1, 0, 1], ["Short", "Zero", "Long"]) plt.legend() if make_file: plt.savefig('./image/' + self.today + cds[0] + ' position_view.png', bbox_inches='tight')
def futures_basis_view(self, df, threshold, cd, size=(15, 7), make_file=False): cds = common.str_list(cd) fig, ax = plt.subplots(figsize=size) x = df.index plt.autoscale(True, axis='both') plt.fill_between(x, df[cds[0]], df[cds[0]] + df['basis'], facecolor='sienna', alpha=0.2) plt.plot(x, df[cds[0]], 'sienna', linestyle='--') plt.plot(x, df[cds[1]], 'C1', lw=3) plt.legend() if make_file: plt.savefig('./image/' + self.today + cds[0] + ' futures_basis_view.png', bbox_inches='tight')
def position_view(self, df, cd, size=(15, 1), make_file=False, file_name=''): cds = common.str_list(cd) fig, ax = plt.subplots(figsize=size) x = df.index for c in cds: df['ps' + c] = 0 df.loc[df['p ' + c] == 'll', ['ps' + c]] = 1 df.loc[df['p ' + c] == 'sl', ['ps' + c]] = 1 df.loc[df['p ' + c] == 'zl', ['ps' + c]] = 1 df.loc[df['p ' + c] == 'ls', ['ps' + c]] = -1 df.loc[df['p ' + c] == 'ss', ['ps' + c]] = -1 df.loc[df['p ' + c] == 'zs', ['ps' + c]] = -1 plt.fill_between(x, df['ps' + c], 0, label=c) plt.yticks([-1, 0, 1], ["Short", "Zero", "Long"]) plt.legend() if make_file: f_name = file_name + '_position_view.png' plt.savefig('./image/' + f_name, bbox_inches='tight')
def multi_line_view(self, df, b_date, cd_a, cd_b, size=(15, 7), make_file=False): cds_a = common.str_list(cd_a) cds_b = common.str_list(cd_b) fig, ax1 = plt.subplots(figsize=size) x = df.loc[b_date:].index i = 1 for c in cds_a: if i == 1: ax1.plot(x, df.loc[b_date:, c], color='C' + str(i), lw=3, label=c) pass else: ax1.plot(x, df.loc[b_date:, c], color='C' + str(i), label=c) i += 1 if cds_b: ax2 = ax1.twinx() i = 6 for c in cds_b: ax2.plot(x, df.loc[b_date:, c], color='C' + str(i), label=c, alpha=0.7) ax1.plot(np.nan, color='C' + str(i), label=c) i += 1 ax1.legend(loc=0) if make_file: plt.savefig('./image/' + self.today + cds_a[0] + ' multi_line_view.png', bbox_inches='tight')
def price_view(self, df, b_date, cd, size=(15, 7), make_file=False): cds = common.str_list(cd) fig, ax = plt.subplots(figsize=size) x = df.loc[b_date:].index for c in cds: plt.plot(x, df.loc[b_date:, c], label=c) plt.legend() if make_file: plt.savefig('./image/' + self.today + cds[0] + ' price_view.png', bbox_inches='tight')
def BB_trend_view(self, df, cd, size=(15, 7), make_file=False): cds = common.str_list(cd) fig, ax = plt.subplots(figsize=size) x = df.index plt.fill_between(x, df['lb'], df['ub'], facecolor='sienna', alpha=0.2) plt.plot(x, df['center'], color='sienna', linestyle='--', label='MA') plt.plot(x, df[cds[0]], color='C0', linestyle='-', lw=3) plt.legend() if make_file: plt.savefig('./image/' + self.today + cds[0] + ' bb_trend_view.png', bbox_inches='tight')
def benchmark_return(self, book, s_cd, report_name='', report={}): # 벤치마크 수익률 cds = common.str_list(s_cd) n = len(cds) rtn = dict() acc_rtn = float() for c in cds: rtn[c] = round( (book[c].iloc[-1] - book[c].iloc[0]) / book[c].iloc[0] + 1, 4) acc_rtn += rtn[c] / n print('BM return:', round((acc_rtn - 1) * 100, 2), '%', rtn) if not report == {}: report['BM_rtn'] = (round((acc_rtn - 1) * 100, 2)) report['BM_rtn_A'] = (round(rtn[cds[0]] * 100, 2)) report['BM_rtn_B'] = (round(rtn[cds[1]] * 100, 2)) return round(acc_rtn, 4)
def index_view(self, df, b_date, cd, size=(15, 7), make_file=False): if isinstance(df.index[0], dt.date): b_date = common.check_base_date(df, b_date) fig, ax = plt.subplots(figsize=size) # fig, ax = plt.subplots(figsize=size) x = df.loc[b_date:].index cds = common.str_list(cd) for c in cds: plt.plot(x, df.loc[b_date:, c] / df.loc[b_date, c] * 100, label=c) plt.legend() plt.show() if make_file: plt.savefig('./image/' + self.today + cds[0] + ' index_view.png', bbox_inches='tight')
def BB_trend_view(self, sample, sigma, s_cd, make_file=False, size=(15, 7)): cds = common.str_list(s_cd) fig, ax = plt.subplots(figsize=size) x = sample.index plt.fill_between(x, sample['lb'], sample['ub'], facecolor='sienna', alpha=0.2) plt.plot(x, sample['center'], color='sienna', linestyle='--', label='MA') plt.plot(x, sample[cds[0]], color='C0', linestyle='-', lw=3) x_length = len(x) jump = int(x_length / 10) xs = list() for i in range(10): xs.append(x[jump * i]) xs.append(x[-1]) plt.xticks(np.arange(0, x_length + jump, jump), xs, rotation=45) plt.legend() if make_file: plt.savefig('./image/' + VisualizeIntraday.today + cds[0] + ' bb_trend_view.png', bbox_inches='tight')
def returns(self, book, s_cd, display=False, report_name='', report={}, fee=0.0): # 손익 계산 cds = common.str_list(s_cd) rtn = 1.0 book['return'] = 1 no_trades = 0 no_win = 0 for c in cds: buy = 0.0 sell = 0.0 for i in book.index: if book.loc[i, 'p ' + c] == 'zl' or book.loc[i, 'p ' + c] == 'sl': # long 진입 buy = book.loc[i, c] if fee > 0.0: buy = round(buy * (1 + fee), 3) if display: print(i, 'long ' + c, buy) elif book.loc[i, 'p ' + c] == 'lz' or book.loc[i, 'p ' + c] == 'ls': # long 청산 sell = book.loc[i, c] if fee > 0.0: sell = round(sell * (1 - fee), 3) # 손익 계산 rtn = sell / buy book.loc[i, 'return'] = rtn no_trades += 1 if rtn > 1: no_win += 1 if display: print(i, 'long ' + c, buy, ' | unwind long ' + c, sell, ' | return: %0.2f' % (round(rtn - 1, 4) * 100)) elif book.loc[i, 'p ' + c] == 'zs' or book.loc[i, 'p ' + c] == 'ls': # short 진입 sell = book.loc[i, c] if fee > 0.0: sell = sell * (1 - fee) if display: print(i, 'short ' + c, sell) elif book.loc[i, 'p ' + c] == 'sz' or book.loc[i, 'p ' + c] == 'sl': # short 청산 buy = book.loc[i, c] if fee > 0.0: buy = buy * (1 + fee) # 손익 계산 rtn = buy / sell book.loc[i, 'return'] = rtn no_trades += 1 if rtn > 1: no_win += 1 if display: print(i, 'short ' + c, sell, ' | unwind short ' + c, buy, ' | return: %0.2f' % (round(rtn - 1, 4) * 100)) if book.loc[i, 't ' + c] == '' and book.loc[i, 'p ' + c] == '': # zero position buy = 0.0 sell = 0.0 # Accumulated return acc_rtn = 1.0 for i in book.index: rtn = book.loc[i, 'return'] acc_rtn = acc_rtn * rtn book.loc[i, 'acc return'] = acc_rtn first_day = pd.to_datetime(book.index[0]) last_day = pd.to_datetime(book.index[-1]) total_days = (last_day - first_day).days annualizer = total_days / 365 print(common.FontStyle.bg_white + 'Accumulated return:', round((acc_rtn - 1) * 100, 2), '%' + common.FontStyle.end_bg, \ ' ( # of trade:', no_trades, ', # of win:', no_win, ', fee: %.2f' % (fee * 100), \ '%,', 'period: %.2f' % annualizer, 'yr )') if no_trades > 0: avg_rtn = acc_rtn**(1 / no_trades) prob_win = round((no_win / no_trades), 4) else: avg_rtn = 1.0 prob_win = 0.0 avg_rtn = round(avg_rtn, 4) bet = common.Bet() kelly_ratio = bet.kelly_formular(prob_win) kelly_ratio = round(kelly_ratio, 4) print('Avg return: %.2f' % ((avg_rtn - 1) * 100), end=' %') if prob_win > 0.5: print(common.FontStyle.orange, end='') print(', Prob. of win: %.2f' % (prob_win * 100), end=' %') if prob_win > 0.5: print(common.FontStyle.end_c, end='') print(', Kelly ratio: %.2f' % (kelly_ratio * 100), end=' %') mdd = round((book['return'].min()), 4) print(', MDD: %.2f' % ((mdd - 1) * 100), '%') if not report == {}: report['acc_rtn'] = round((acc_rtn) * 100, 2) report['no_trades'] = no_trades report['avg_rtn'] = round((avg_rtn * 100), 2) report['prob_win'] = round((prob_win * 100), 2) report['kelly_ratio'] = round((kelly_ratio * 100), 2) report['fee'] = round((fee * 100), 2) report['mdd'] = round((mdd * 100), 2) return round(acc_rtn, 4)