def analyze_atm(): filename = 'strategyAtmReturnNextTradedayOpen.csv' fp = getTestPath(filename) df = pd.read_csv(fp, index_col=0, parse_dates=True) # df = df.groupby('tradeDay').apply(analyze_single_atm) df = df.groupby('tradeDay').apply(analyze_single_atm_open) grouped = df.groupby('time_flag') groupedDict = dict(list(grouped)) keys = groupedDict.keys() keys.sort() print(u'昨日平值期权今日开盘n分钟后,价和与昨日收盘对比统计情况统计结果(单位:元):') for key in keys: print('' * 30) df = groupedDict[key] # if key != '0-minute': if key == '1-minute': all_count = len(df) higer_count = len(df[df.abs_change > 0]) lower_count = len(df[df.abs_change <= 0]) min = df.abs_change.min() max = df.abs_change.max() mean = df.abs_change.mean() median = df.abs_change.median() df2 = df.iloc[-240:] volume_mean = df2.volume.mean() print('-' * 30) print(u'开盘%s分钟后:' % key[0]) print('-' * 30) print(u'总交易日:%s' % all_count) print(u'价和比昨收盘更高交易日:%s' % higer_count) print(u'价和比昨收盘更低交易日:%s' % lower_count) print(u'价和跌最低:%.2f' % (min * 10000)) print(u'价和涨最高:%.2f' % (max * 10000)) print(u'价和涨跌平均值:%.2f' % (mean * 10000)) print(u'价和涨跌中位数:%.2f' % (median * 10000)) print(u'近一年成交量平均值:%.2f' % volume_mean) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title(key) ax.set_ylabel('trade_days') df.abs_change.hist(bins=200, ax=ax) filename = '{}_open.png'.format(key) fig.savefig(getTestPath(filename))
def testGetNearbyContract(self): # filename = 'option_daily_2018-12-07.csv' filename = 'option_daily_2018-12-25.csv' fp = os.path.join(self.obj.jqsdk.getPricePath('option', 'daily'), filename) df = self.obj.getNearbyContract(fp) df.to_csv(getTestPath('nearbyContract.csv'))
def testGetOHLC(self): # method = 'match' # df = self.obj.getOHLCdaily(method=method) # df.to_csv(getTestPath('atm_ohlc_{}.csv'.format(method))) method = 'match' df = self.obj.getOHLCdaily(method=method, isIncludePre=True) df.to_csv(getTestPath('atm_ohlc_{}_includePre.csv'.format(method)))
def plot_test_date_kline(filename): fp = getTestPath(filename) df = pd.read_csv(fp, index_col=0) plotter = KlinePlotter(df) plotter.plotAll('atm-ohlc-no-gap-test', 'dailytask', 'atm-ohlc-no-gap-test.html', item=['ma'])
def testGetVolatility(self): stats_df = [] for n in [10, 20, 30, 60, 90]: self.obj.getHistVolatility(n) name = 'HV_{}'.format(n) stats_df.append(self.obj.price[name]) # print(self.obj.price[name].describe()) self.obj.price.to_csv(getTestPath('510050_hist_volatility.csv'))
def testGetPrice(self): begin = datetime(2018, 11, 22) end = datetime(2018, 11, 23) # df = self.obj.get_price('RB9999.XSGE', start_date='2018-11-22', end_date='2018-12-01', frequency='1m') df = self.obj.get_price('CU9999.XSGE', start_date=begin, end_date=end, frequency='1m') df.to_csv(fn.getTestPath('testjq.csv'), encoding='utf-8-sig') print(df.iloc[0]) print(df.iloc[-1])
def testGetAtmContract(self): filename = 'option_daily_2019-04-10.csv' fp = os.path.join(self.obj.jqsdk.getPricePath('option', 'daily'), filename) # df = self.obj.getAtmContract(fp) # df.to_csv(getTestPath('atmContract.csv')) # df2 = self.obj.getStraddleContract(fp) # df2.to_csv(getTestPath('straddle.csv')) df3 = self.obj.getAssignedContract(fp, 3300, 2700) df3.to_csv(getTestPath('assigned.csv'))
def analyze_atm_range(start_time, end_time): start_l = start_time.split(':') start_time = time(int(start_l[0]), int(start_l[1])) end_l = end_time.split(':') end_time = time(int(end_l[0]), int(end_l[1])) filename = 'atm_continuous_bar.csv' fp = os.path.join(getDataDir(), 'research', 'option', 'dailytask', 'atm_continuous_bar.csv') df = pd.read_csv(fp, index_col=0, parse_dates=True) df = df.groupby('tradeDay').apply(analyze_single_atm_range, start_time, end_time) all_count = len(df) higer_count = len(df[df.abs_change > 0]) lower_count = len(df[df.abs_change <= 0]) min = df.abs_change.min() max = df.abs_change.max() mean = df.abs_change.mean() median = df.abs_change.median() # df2 = df.iloc[-240:] # volume_mean = df2.volume.mean() print('-' * 30) print(u'昨日平值期权今日%s-%s价和对比:' % (':'.join(start_l), ':'.join(end_l))) print('-' * 30) print(u'总交易日:%s' % all_count) print(u'后面的时间价和更高交易日:%s' % higer_count) print(u'后面的时间价和更低交易日:%s' % lower_count) print(u'价和跌最低:%.2f' % (min * 10000)) print(u'价和涨最高:%.2f' % (max * 10000)) print(u'价和涨跌平均值:%.2f' % (mean * 10000)) print(u'价和涨跌中位数:%.2f' % (median * 10000)) # print(u'近一年成交量平均值:%.2f' % volume_mean) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title(u'%s-%s' % (':'.join(start_l), ':'.join(end_l))) ax.set_ylabel('trade_days') df.abs_change.hist(bins=100, ax=ax) filename = '{}_open.png'.format( u'%s-%s' % (start_time.strftime('%H%M'), end_time.strftime('%H%M'))) fig.savefig(getTestPath(filename))
def analyze_qvix_high_close(): df = load_qvix_data() all_trade_days = len(df) df['h-c'] = df['high'] - df['close'] df['h-c-ratio'] = (df['h-c'] / df['close']) * 100 df2 = df[df['h-c'] > 0] df = copy(df2) h_gt_o_trade_days = len(df) for i in [5, 10, 20]: h_o_name = 'h-c-ma-{}'.format(i) df[h_o_name] = df['h-c'].rolling(i).mean() h_o_ratio_name = 'h-c-ratio-ma-{}'.format(i) df[h_o_ratio_name] = df['h-c-ratio'].rolling(i).mean() new_file = 'vix_bar_high_close_ma.csv' fp2 = os.path.join(getDataDir(), RESEARCH, OPTION, 'qvix', new_file) df.to_csv(fp2) print('-' * 30) print(u'自2016-6-13以来,期权论坛波值最高价大于收盘价的交易统计:') print('-' * 30) print(u'总交易日:%s' % all_trade_days) print(u'最高价大于收盘价的交易日:%s, 占比:%.3f %%' % (h_gt_o_trade_days, (float(h_gt_o_trade_days) / float(all_trade_days)) * 100)) for n in range(0, 15): df_n = df[df['h-c-ratio'] > n] c_n = len(df_n) print(u'最高价对比收盘价百分比超过%s交易日:%s,占比:%.3f %%' % (n, c_n, (float(c_n) / float(h_gt_o_trade_days)) * 100)) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title(u'Ratio(High To Close) Distribution') ax.set_ylabel('trade_days') df['h-c-ratio'].hist(bins=100, ax=ax) filename = '{}_open.png'.format('high_gt_close') fig.savefig(getTestPath(filename))
def testGetEtfRatio(self): df = self.obj.getEtfMarketRatio() df.to_csv(getTestPath('etfRatio.csv'))
def testGetRatio(self): df = self.obj.getRatio() df.to_csv(getTestPath('ratio.csv'), encoding='utf-8-sig')
def testStrategyAtmReturnNextTradedayOpen(self): df = self.obj.strategyAtmReturnNextTradedayOpen( '2017-01-01', '2019-05-10') df.to_csv(getTestPath('strategyAtmReturnNextTradedayOpen.csv'))
def testGetHistVol(self): self.obj.getHisVolatility(20) df = self.obj.getVix() df.to_csv(getTestPath('vix_hist_vol_test.csv'))
def testGetPercentile(self): print(self.obj.getVixPercentile()) self.obj.vix.to_csv(getTestPath('vix_test.csv'))
def testGetPosition(self): df = self.obj.getPosition() df.to_csv(getTestPath('position.csv'), encoding='utf-8-sig')
def testGetContractInfo(self): df = self.obj.getContractInfo() print(self.obj.contractInfo) df.to_csv(getTestPath('contractInfo.csv'), encoding='utf-8-sig')
def testAdd50etf(self): df = self.obj.add50etf() print(df) df.to_csv(getTestPath('50etf-qvix.csv'))
def testMonteCarlo(self): df = self.obj.monteCarloSim(100, 21) df.to_csv(getTestPath('montecarlo.csv'))
def testGetDailyPrice(self): contract = '10001562.XSHG' df = self.obj.getDailyPrice(contract) df.to_csv(getTestPath('optionPrice.csv'), encoding='utf-8-sig')
def testGetStraddleContract(self): level = 1 df = self.obj.getStraddleContract(self.fp, method='match', level=level) df.to_csv(getTestPath('straddle{}_contract_match.csv'.format(level)))
def testGetAtmContract(self): df = self.obj.getAtmContract(self.fp, method='match') df.to_csv(getTestPath('atm_contract_match.csv')) df = self.obj.getAtmContract(self.fp, method='simple') df.to_csv(getTestPath('atm_contract_simple.csv'))
def testGetNearbyContract(self): df = self.obj.getNearbyContract(self.fp) df.to_csv(getTestPath('nearbyContract_20190225.csv'))
def testGetMoneyFlowOf50EtfInPeriod(self): d1 = datetime(2019, 2, 25) d2 = datetime.today() d3 = datetime(2019, 3, 1) df = self.obj.getMoneyFlowOf50Etf(d1, d3) df.to_csv(getTestPath('50etf_money_flow.csv'))
def testGetCompContract(self): df = self.obj.getCompContract() df.to_csv(getTestPath('optionDisplayContract.csv'), encoding='utf-8-sig')
def testGetHVPercentile(self): self.obj.getHVPercentile(20) df = self.obj.getVix() df.to_csv(getTestPath('HV20_percentile.csv'))
def testGetTradingContractInfo(self): df = self.obj.getTradingContract() df.to_csv(getTestPath('optionTradingContract.csv'), encoding='utf-8-sig')
def testAddHisVol(self): s = self.obj.addHistVolotility(20) print(s) self.obj.dailyData.to_csv(getTestPath('50etf-hisvol.csv'))
def testStrategyAtmLastTradeDays(self): df = self.obj.strategyAtmLastTradeDays() df.to_csv(getTestPath('strategyAtmLastTradeDays.csv'))
def testRemoveGap(self): df = self.obj.removeOHLCgap() df.to_csv(getTestPath('test_atm_ohlc_remove_gap.csv'))
def testGetMainContractDailyPrice(self): price = self.obj.getAllContractDailyPrice() for code, df in price.items(): fp = getTestPath('{}.csv'.format(code)) df.to_csv(fp, encoding='utf-8-sig')