def df_hv(code, date): try: now = datetime.now() start_day = now - timedelta(days=480) start_day = start_day.strftime('%Y-%m-%d') if code[:2] == 'IO': df = get_inx('000300', start_day) else: fn = get_dss() + 'fut/bar/day_' + code + '.csv' df = pd.read_csv(fn) df = df[(df.date >= start_day) & (df.date <= date)] df = df.set_index('date') df = df.sort_index() df['ln'] = np.log(df.close) df['rt'] = df['ln'].diff(1) df['hv'] = df['rt'].rolling(20).std() df['hv'] *= np.sqrt(242) * 100 df = df.iloc[-242:, ] df['value'] = df['hv'] df = df[['value']] df.index.name = code + '_hv' return df except Exception as e: s = traceback.format_exc() to_log(s) return None
def get_trade_preday(date): from nature import get_inx df = get_inx('000300') date_list = list(df.date) try: i = date_list.index(date) except: i = -1 return date_list[i + 1]
def calc_hv(date): df = get_inx('000300', '2020-01-01', date) df = df.set_index('date') df = df.sort_index() df['ln'] = np.log(df.close) df['rt'] = df['ln'].diff(1) df['hv'] = df['rt'].rolling(60).std() df['hv'] *= np.sqrt(242) cur = df.iloc[-1, :] return float(cur.hv), float(cur.close)
def hv_show(code): # hv() now = datetime.now() start_day = now - timedelta(days=480) start_day = start_day.strftime('%Y-%m-%d') if code == '000300': df = get_inx('000300', start_day) else: fn = get_dss() + 'fut/bar/day_' + code + '.csv' df = pd.read_csv(fn) df = df[df.date >= start_day] df = df.set_index('date') df = df.sort_index() df['ln'] = np.log(df.close) df['rt'] = df['ln'].diff(1) df['hv'] = df['rt'].rolling(20).std() df['hv'] *= np.sqrt(242) df = df.iloc[-242:, :] cur = df.iloc[-1, :] hv = round(cur['hv'], 2) hv_rank = round((hv - df['hv'].min()) / (df['hv'].max() - df['hv'].min()), 2) hv_percentile = round(len(df[df.hv < hv]) / 242, 2) plt.figure(figsize=(13, 7)) plt.title(code + ' hv: ' + str(hv) + ' hv Rank: ' + str(hv_rank) + ' hv Percentile: ' + str(hv_percentile)) plt.xticks(rotation=90) plt.plot(df['hv'], '-*') plt.grid(True, axis='y') ax = plt.gca() for label in ax.get_xticklabels(): label.set_visible(False) for label in ax.get_xticklabels()[1::30]: label.set_visible(True) for label in ax.get_xticklabels()[-1:]: label.set_visible(True) fn = 'static/hv_show.jpg' plt.savefig(fn) plt.cla() r = '' fn = 'hv_show.jpg' now = str(int(time.time())) r = '<img src=\"static/' + fn + '?rand=' + now + '\" />' return r
def hs300_spread_show(start_day): df_300 = get_inx('000300', start_day) df_300 = df_300.set_index('date') df_300 = df_300.sort_index() # print(df_300.tail()) fn = get_dss() + 'fut/cfg/opt_mature.csv' df_opt = pd.read_csv(fn) df = df_opt[(df_opt.pz == 'IO') & (df_opt.flag == df_opt.flag)] # 筛选出不为空的记录 df = df.sort_values('symbol') symbol_list = list(df.symbol) # print(symbol_list) plt.figure(figsize=(12, 8)) plt.title('hs300_spread') for symbol in symbol_list: code = 'IF' + symbol[2:] fn = get_dss() + 'fut/bar/day_' + code + '.csv' if os.path.exists(fn) == False: continue df = pd.read_csv(fn) df = df[df.date >= start_day] df = df.set_index('date') df = df.sort_index() df['value'] = df.close - df_300.close # print(df.tail()) plt.plot(df.value, label=code) plt.xticks(rotation=45) plt.grid(True, axis='y') ax = plt.gca() # for label in ax.get_xticklabels(): # label.set_visible(False) # for label in ax.get_xticklabels()[1::25]: # label.set_visible(True) # for label in ax.get_xticklabels()[-1:]: # label.set_visible(True) plt.legend() fn = 'static/hs300_spread_show.jpg' plt.savefig(fn) plt.cla() r = '' fn = 'hs300_spread_show.jpg' now = str(int(time.time())) r = '<img src=\"static/' + fn + '?rand=' + now + '\" />' return r
def hv(): # df = get_inx('000300', '2019-06-01', '2020-07-15') df = get_inx('000300', '2019-06-01') # df = df.sort_values('date') df = df.set_index('date') df = df.sort_index() df['ln'] = np.log(df.close) df['rt'] = df['ln'].diff(1) df['hv'] = df['rt'].rolling(20).std() df['hv'] *= np.sqrt(242) df = df.iloc[-242:, :] # print(df.head()) # print(df.tail()) cur = df.iloc[-1, :] hv = round(cur['hv'], 2) hv_rank = round((hv - df['hv'].min()) / (df['hv'].max() - df['hv'].min()), 2) # print('hv: ', hv) # print('hv Rank: ', hv_rank) # print(' 均值:',df['hv'].mean()) # print('0.2分位数:',np.percentile(df['hv'], 20)) # print('0.5分位数:',np.percentile(df['hv'], 50)) # print('0.8分位数:',np.percentile(df['hv'], 80)) hv_percentile = round(len(df[df.hv < hv]) / 242, 2) # print('hv percentile: ', hv_percentile) plt.figure(figsize=(13, 7)) plt.title('hv:' + str(hv) + ' hv Rank:' + str(hv_rank) + ' hv Percentile:' + str(hv_percentile)) plt.xticks(rotation=45) plt.plot(df['hv'], '-*') plt.grid(True, axis='y') ax = plt.gca() for label in ax.get_xticklabels(): label.set_visible(False) for label in ax.get_xticklabels()[1::30]: label.set_visible(True) for label in ax.get_xticklabels()[-1:]: label.set_visible(True) # plt.show() fn = 'static/vol_hv.jpg' plt.savefig(fn) plt.cla()
def calc_greeks(year): c = input('请确认波指已维护最新值,press y to continue: ') if c != 'y': return fn_sigma = get_dss() + 'backtest/IO/hs300波指.csv' df_sigma = pd.read_csv(fn_sigma) df_sigma = df_sigma.set_index('date') mature_dict = {'IO2002':'2020-02-21','IO2003':'2020-03-20','IO2004':'2020-04-17','IO2005':'2020-05-15','IO2006':'2020-06-19', 'IO2007':'2020-07-17','IO2009':'2020-09-18','IO2012':'2020-12-18','IO2103':'2021-03-19'} fn1 = get_dss() + 'backtest/IO/' + 'IO' + year + '.csv' fn2 = get_dss() + 'backtest/IO/' + 'IO' + year + '_greeks.csv' df1 = pd.read_csv(fn1) df2 = pd.read_csv(fn2) df1 = df1.loc[len(df2):,:] # print(df1.head(3)) for i, row in df1.iterrows(): df_index = get_inx('000300', row.date, row.date) if len(df_index) == 0: print('缺少沪深300日线数据') assert False S0 = df_index.iat[0,3] # S0 = 3912.57 call = True if row['symbol'][7] == 'C' else False K = float( row['symbol'][-4:] ) r = 0.03 C0 = float( row['close'] ) sa = float( df_sigma.at[row.date, 'close'] ) / 100 # sa = 0.2178 # print(sa) if row['symbol'][:6] not in mature_dict.keys(): assert False date_mature = mature_dict[ row['symbol'][:6] ] date_mature = datetime.datetime.strptime(date_mature, '%Y-%m-%d') today = datetime.datetime.strptime(row.date, '%Y-%m-%d') T = float((date_mature - today).days) / 365 if T > 0: if call == True: n = 1 iv = bsm_call_imp_vol(S0, K, T, r, C0) else: n = -1 iv = bsm_put_imp_vol(S0, K, T, r, C0) row['hs300'] = S0 row['sigma'] = sa row['delta9'] = delta(S0,K,r,T,sa,n) row['gamma'] = gamma(S0,K,r,T,sa) row['theta'] = theta(S0,K,r,T,sa,n) row['vega'] = vega(S0,K,r,T,sa) row['iv'] = iv else: row['hs300'] = S0 row['delta9'] = 0 row['gamma'] = 0 row['theta'] = 0 row['vega'] = 0 row['sigma'] = 0 df = pd.DataFrame([row]) df.to_csv(fn2, index=False, mode='a', header=None)