예제 #1
0
파일: c5.py 프로젝트: 3774257/abu
def sample_52():
    """
    5.2 使用bokeh交互可视化
    :return:
    """
    from abupy import ABuMarketDrawing
    ABuMarketDrawing.plot_candle_form_klpd(tsla_df, html_bk=True)
예제 #2
0
파일: c4.py 프로젝트: 3774257/abu
def sample_415():
    """
    4.1.5 重采样数据
    :return
    """
    days = pd.date_range('2017-1-1',
                         periods=stock_day_change.shape[1], freq='1d')
    stock_symbols = ['股票 ' + str(x) for x in
                     xrange(stock_day_change.shape[0])]
    df = pd.DataFrame(stock_day_change, index=stock_symbols, columns=days)
    df = df.T
    df_stock0 = df['股票 0']

    # 以5天为周期重采样(周k)
    df_stock0_5 = pd_resample(df_stock0.cumsum(), '5D', how='ohlc')
    # 以21天为周期重采样(月k),
    # noinspection PyUnusedLocal
    df_stock0_20 = pd_resample(df_stock0.cumsum(), '21D', how='ohlc')
    # 打印5天重采样,如下输出2017-01-01, 2017-01-06, 2017-01-11, 表4-6所示
    print('df_stock0_5.head():\n', df_stock0_5.head())

    from abupy import ABuMarketDrawing
    # 图4-2所示
    ABuMarketDrawing.plot_candle_stick(df_stock0_5.index,
                                       df_stock0_5['open'].values,
                                       df_stock0_5['high'].values,
                                       df_stock0_5['low'].values,
                                       df_stock0_5['close'].values,
                                       np.random.random(len(df_stock0_5)),
                                       None, 'stock', day_sum=False,
                                       html_bk=False, save=False)

    print('type(df_stock0_5.open.values):', type(df_stock0_5['open'].values))
    print('df_stock0_5.open.index:\n', df_stock0_5['open'].index)
    print('df_stock0_5.columns:\n', df_stock0_5.columns)
예제 #3
0
def sample_52():
    """
    5.2 使用bokeh交互可视化
    :return:
    """
    from abupy import ABuMarketDrawing
    ABuMarketDrawing.plot_candle_form_klpd(tsla_df, html_bk=True)
예제 #4
0
def sample_45_2():
    """
    4.5 实例3 :跳空缺口
    :return:
    """
    # axis=1即行数据,tsla_df的每一条行数据即为每一个交易日数据
    tsla_df.apply(judge_jump, axis=1)
    print('jump_pd:\n', jump_pd)

    from abupy import ABuMarketDrawing
    # view_indexs传入jump_pd.index,即在k图上使用圆来标示跳空点
    ABuMarketDrawing.plot_candle_form_klpd(tsla_df, view_indexs=jump_pd.index)
    plt.show()
예제 #5
0
파일: c4.py 프로젝트: 3774257/abu
def sample_45_2():
    """
    4.5 实例3 :跳空缺口
    :return:
    """
    # axis=1即行数据,tsla_df的每一条行数据即为每一个交易日数据
    tsla_df.apply(judge_jump, axis=1)
    print('jump_pd:\n', jump_pd)

    from abupy import ABuMarketDrawing
    # view_indexs传入jump_pd.index,即在k图上使用圆来标示跳空点
    ABuMarketDrawing.plot_candle_form_klpd(tsla_df, view_indexs=jump_pd.index)
    plt.show()
예제 #6
0
파일: c11.py 프로젝트: 3774257/abu
def sample_111():
    """
    11.1 搜索引擎与量化交易

    请对照阅读ABU量化系统使用文档 :第16节 UMP主裁交易决策 中相关内容

    :return:
    """
    abu_result_tuple_train, abu_result_tuple_test, metrics_train, metrics_test = load_abu_result_tuple()
    orders_pd_train = abu_result_tuple_train.orders_pd

    # 选择失败的前20笔交易绘制交易快照
    # 这里只是示例,实战中根据需要挑选,rank或者其他方式
    plot_simple = orders_pd_train[orders_pd_train.profit_cg < 0][:20]
    # save=True保存在本地,文件保存在~/abu/data/save_png/中
    ABuMarketDrawing.plot_candle_from_order(plot_simple, save=True)
예제 #7
0
def sample_c2():
    """
    C.2 量化技术指标应用: 对量化策略失败结果的人工分析
    :return:
    """
    abupy.env.disable_example_env_ipython()

    # 从之前章节的缓存中读取交易数据
    abu_result_tuple_train = abu.load_abu_result_tuple(
        n_folds=5,
        store_type=EStoreAbu.E_STORE_CUSTOM_NAME,
        custom_name='train_cn')
    # 只筛选orders中有交易结果的单子
    has_result = abu_result_tuple_train.orders_pd[
        abu_result_tuple_train.orders_pd.result == -1]

    # 随便拿一个交易数据作为示例
    sample_order = has_result.ix[100]
    _ = ABuMarketDrawing.plot_candle_from_order(sample_order)

    nd.macd.plot_macd_from_order(sample_order, date_ext=252)
    nd.boll.plot_boll_from_order(has_result.ix[100], date_ext=252)
    nd.ma.plot_ma_from_order(has_result.ix[100],
                             date_ext=252,
                             time_period=[10, 20, 30, 60, 90, 120])
예제 #8
0
def sample_111():
    """
    11.1 搜索引擎与量化交易

    请对照阅读ABU量化系统使用文档 :第16节 UMP主裁交易决策 中相关内容

    :return:
    """
    abu_result_tuple_train, abu_result_tuple_test, metrics_train, metrics_test = load_abu_result_tuple(
    )
    orders_pd_train = abu_result_tuple_train.orders_pd

    # 选择失败的前20笔交易绘制交易快照
    # 这里只是示例,实战中根据需要挑选,rank或者其他方式
    plot_simple = orders_pd_train[orders_pd_train.profit_cg < 0][:20]
    # save=True保存在本地,文件保存在~/abu/data/save_png/中
    ABuMarketDrawing.plot_candle_from_order(plot_simple, save=True)
예제 #9
0
def sample_415():
    """
    4.1.5 重采样数据
    :return
    """
    days = pd.date_range('2017-1-1',
                         periods=stock_day_change.shape[1],
                         freq='1d')
    stock_symbols = ['股票 ' + str(x) for x in xrange(stock_day_change.shape[0])]
    df = pd.DataFrame(stock_day_change, index=stock_symbols, columns=days)
    df = df.T
    df_stock0 = df['股票 0']

    # 以5天为周期重采样(周k)
    df_stock0_5 = pd_resample(df_stock0.cumsum(), '5D', how='ohlc')
    # 以21天为周期重采样(月k),
    # noinspection PyUnusedLocal
    df_stock0_20 = pd_resample(df_stock0.cumsum(), '21D', how='ohlc')
    # 打印5天重采样,如下输出2017-01-01, 2017-01-06, 2017-01-11, 表4-6所示
    print('df_stock0_5.head():\n', df_stock0_5.head())

    from abupy import ABuMarketDrawing
    # 图4-2所示
    ABuMarketDrawing.plot_candle_stick(df_stock0_5.index,
                                       df_stock0_5['open'].values,
                                       df_stock0_5['high'].values,
                                       df_stock0_5['low'].values,
                                       df_stock0_5['close'].values,
                                       np.random.random(len(df_stock0_5)),
                                       None,
                                       'stock',
                                       day_sum=False,
                                       html_bk=False,
                                       save=False)

    print('type(df_stock0_5.open.values):', type(df_stock0_5['open'].values))
    print('df_stock0_5.open.index:\n', df_stock0_5['open'].index)
    print('df_stock0_5.columns:\n', df_stock0_5.columns)
예제 #10
0
파일: extC.py 프로젝트: 3774257/abu
def sample_c2():
    """
    C.2 量化技术指标应用: 对量化策略失败结果的人工分析
    :return:
    """
    abupy.env.disable_example_env_ipython()

    # 从之前章节的缓存中读取交易数据
    abu_result_tuple_train = abu.load_abu_result_tuple(n_folds=5, store_type=EStoreAbu.E_STORE_CUSTOM_NAME,
                                                       custom_name='train_cn')
    # 只筛选orders中有交易结果的单子
    has_result = abu_result_tuple_train.orders_pd[
        abu_result_tuple_train.orders_pd.result == -1]

    # 随便拿一个交易数据作为示例
    sample_order = has_result.ix[100]
    _ = ABuMarketDrawing.plot_candle_from_order(sample_order)

    nd.macd.plot_macd_from_order(sample_order, date_ext=252)
    nd.boll.plot_boll_from_order(has_result.ix[100], date_ext=252)
    nd.ma.plot_ma_from_order(has_result.ix[100], date_ext=252, time_period=[10, 20, 30, 60, 90, 120])
예제 #11
0
        if i == 0:
            emas[i] = cps[i]
        if i > 0:
            emas[i] = ((days - 1) * emas[i - 1] + 2 * cps[i]) / (days + 1)
    return emas


stock_k['ema10'] = get_EMA(stock_k.close, 10)
stock_k['ema60'] = get_EMA(stock_k.close, 60)
plt.plot(stock_k.ema10, c='r')
plt.plot(stock_k.ema60, c='green')
plt.plot(stock_k.close, c='blue')
plt.show()

from abupy import ABuMarketDrawing
ABuMarketDrawing.plot_candle_form_klpd(stock_k, html_bk=False)

print('test2')

stock_table = pd.DataFrame()

df = ts.get_tick_data(stock_code, date='2019-2-25', src='tt')  #获取详细数据

for current_date in stock_k.index:
    # 通过loc选中K线图中对应current_date这天的数据
    current_k_line = stock_k.loc[current_date]

    # 提取这一天前10分钟股票信息
    df = ts.get_tick_data(stock_code, date=current_date, src='tt')
    df['time'] = pd.to_datetime(current_date + ' ' + df['time'])
    t = pd.to_datetime(current_date).replace(hour=9, minute=40)
예제 #12
0
파일: play.py 프로젝트: kangni/quant_play
#%%
df_stock0 = df['stock0']
df_stock0.head()
df_stock0.cumsum().plot()

#%%
df_stock0_5 = df_stock0.cumsum().resample('5D').ohlc()
df_stock0_20 = df_stock0.cumsum().resample('21D').ohlc()
df_stock0_5.head()

#%%
ABuMarketDrawing.plot_candle_stick(df_stock0_5.index,
                                   df_stock0_5['open'].values,
                                   df_stock0_5['high'].values,
                                   df_stock0_5['low'].values,
                                   df_stock0_5['close'].values,
                                   np.random.random(len(df_stock0_5)),
                                   None, 'stock', day_sum=False,
                                   html_bk=False, save=False)

#%%
print(type(df_stock0_5['open'].values))
print(df_stock0_5['open'].index)
print(df_stock0_5.columns)

#%%
tsla_df = ABuSymbolPd.make_kl_df('usTSLA', n_folds=3)
tsla_df.tail()
tsla_df[['close', 'volume']].plot(subplots=True, style=['r', 'g'], grid=True)

#%%
예제 #13
0
# 2018-01-16 -6.890551 -6.091618 -6.890551 -6.827189
# 2018-01-21 -5.682790 -5.682790 -8.021937 -7.980051
"""
下面的代码使用abu量化系统中的ABuMarketDrawing.plot_candle_stick()方法,将数据的高开低收K线图绘制出来,
从而得到从日线级别的数据重新构建出轴线的数据,并且可视化
*注意下面K线线图的volum成交量通过np.random.random(len(df_stock5))生成的随机数据进行填充
*k线图的绘制将在数据可视化章节中详细的说明
"""
from abupy import ABuMarketDrawing

ABuMarketDrawing.plot_candle_stick(df_stock5.index,
                                   df_stock5['open'].values,
                                   df_stock5['high'].values,
                                   df_stock5['low'].values,
                                   df_stock5['close'].values,
                                   np.random.random(len(df_stock5)),
                                   None,
                                   'stock',
                                   day_sum=False,
                                   html_bk=False,
                                   save=False)
#结果如图pandas-2所示,类似的可以得到月k线
ABuMarketDrawing.plot_candle_stick(df_stock20.index,
                                   df_stock20['open'].values,
                                   df_stock20['high'].values,
                                   df_stock20['low'].values,
                                   df_stock20['close'].values,
                                   np.random.random(len(df_stock20)),
                                   None,
                                   'stock',
                                   day_sum=False,
예제 #14
0
def plot_order_candle_myself(order, start=60, end=10):
    """
    绘制订单蜡烛图
    :param order: AbuOrder对象序列
    """
    stock_code = order.symbol
    from abupy import code_to_symbol
    sh_stock_code = code_to_symbol(stock_code).value
    all_pd, df_req_start, df_req_end = load_kline_df(sh_stock_code)
    mask_date = all_pd['date'] == order.buy_date
    st_key = all_pd[mask_date]['key']

    if order.sell_type == 'keep':
        rv_pd = all_pd[all_pd.key >= st_key.values[0]]  # 买入到卖出之间的数据
        st_sell_key = all_pd[mask_date]['key']
    else:
        mask_sell_date = all_pd['date'] == order.sell_date  # 卖出日期
        st_sell_key = all_pd[mask_sell_date]['key']  # 卖出日期key
        rv_pd = all_pd[all_pd.key >= st_key.values[0]]
        rv_pd = rv_pd[rv_pd.key < st_sell_key.values[0] + 1]
    tempList = []
    for k in rv_pd.index:
        tempList.append(k)
    if hasattr(order, 'bigWave2Close2'):
        all_pd['bigWave2Close2'] = order.bigWave2Close2
        # all_pd['ema10'] = get_EMA(all_pd.close, 10)
        # all_pd['ema60'] = get_EMA(all_pd.close, 60)
        # tempList.append(order.bigWave2Close2Date)

    from abupy import ABuMarketDrawing
    all_pd = all_pd[all_pd.key >= (st_key.values[0] - start)]
    all_pd = all_pd[all_pd.key < (st_sell_key.values[0] + end)]
    all_pd.name = stock_code
    benchmark = IndexSymbol.SH

    bench_pd = ABuSymbolPd.make_kl_df(
        benchmark,
        data_mode=EMarketDataSplitMode.E_DATA_SPLIT_UNDO,
        n_folds=None,
        start=None,
        end=None)

    bench_mask_date = bench_pd['date'] == order.buy_date  # 买入日期
    bench_st_key = bench_pd[bench_mask_date]['key']  # 买入日期key
    # bench_pd = bench_pd[bench_pd.key > bench_st_key.values[0] - start]
    # bench_pd = bench_pd[bench_pd.key < bench_st_key.values[0] + end]

    if order.sell_type == 'keep':
        rv_pd = bench_pd[bench_pd.key >= bench_st_key.values[0]]  # 买入到卖出之间的数据
        bench_st_sell_key = bench_st_key  # 卖出日期key
    else:
        bench_mask_sell_date = bench_pd['date'] == order.sell_date  # 卖出日期
        bench_st_sell_key = bench_pd[bench_mask_sell_date]['key']  # 卖出日期key
        rv_pd = bench_pd[bench_pd.key >= bench_st_key.values[0]]
        rv_pd = rv_pd[rv_pd.key < bench_st_sell_key.values[0] + 1]

    bench_pd = bench_pd[bench_pd.key >= (bench_st_key.values[0] - start)]
    bench_pd = bench_pd[bench_pd.key <= (bench_st_sell_key.values[0] + end)]

    ABuMarketDrawing.plot_candle_form_klpd(all_pd,
                                           html_bk=False,
                                           view_indexs=tempList,
                                           bench=bench_pd,
                                           order=order,
                                           save=True)
예제 #15
0
파일: lecture19.py 프로젝트: hey0311/abu
import math

import abupy
from abupy import abu, EMarketTargetType, AbuMetricsBase, ABuMarketDrawing, ABuProgress, ABuSymbolPd, get_price, \
    ABuIndustries, AbuDataParseWrap, SupportMixin, ABuNetWork
from abupy import EMarketDataFetchMode, EDataCacheType, EMarketSourceType, FuturesBaseMarket, TCBaseMarket, ABuDateUtil

from abupy.MarketBu.ABuDataFeed import OkexApi
abupy.env.g_data_fetch_mode = EMarketDataFetchMode.E_DATA_FETCH_FORCE_NET
# ABuSymbolPd.make_kl_df('usBIDU').tail()
abupy.env.g_private_data_source = OkexApi
btc=ABuSymbolPd.make_kl_df('btc')
print(btc)
ABuMarketDrawing.plot_candle_form_klpd(btc)
예제 #16
0
# df_stock0=Trydataframe6['股票0']
# print(df_stock0)
# dt_stock0_draw = df_stock0.cumsum().plot()
# plt.show()

Trydataframe6_5 = Trydataframe6.resample('21D', how='ohlc')['股票0']
# print(Trydataframe6_5)
# print(Trydataframe6_5['open'])
print(Trydataframe6_5.columns)

ABuMarketDrawing.plot_candle_stick(Trydataframe6_5.index,
                                   Trydataframe6_5['open'].values,
                                   Trydataframe6_5['high'].values,
                                   Trydataframe6_5['low'].values,
                                   Trydataframe6_5['close'].values,
                                   np.random.random(len(Trydataframe6_5)),
                                   None,
                                   'stock',
                                   day_sum=False,
                                   html_bk=False,
                                   save=False)
# print(stock_day_change)
# print(stock_day_change[0:2,:5])
# tmp=stock_day_change[0:1,:5].copy()
# stock_day_change[0:2,0:5]=stock_day_change[-2:,-5:]
# print(stock_day_change[0:2,0:5],stock_day_change[-2:,-5:])
# mask = stock_day_change[0:2,0:5]>0.5
# print(mask)
# tmp_test = stock_day_change[0:2,0:5].copy()
# aa = tmp_test[mask]
# print(mask,aa)
예제 #17
0
        zip(tsla_part_df.index, tsla_part_df.open, tsla_part_df.close,
            tsla_part_df.high, tsla_part_df.low)):
    d = mpf.date2num(d)
    val = (d, o, c, h, l)
    quotes.append(val)
mpf.candlestick_ochl(ax,
                     quotes,
                     width=0.6,
                     colorup=__colorup__,
                     colordown=__colordown__)
ax.autoscale_view()
ax.xaxis_date()

# 引用 Bokeh 支持交互可视化
from abupy import ABuMarketDrawing
ABuMarketDrawing.plot_candle_form_klpd(tsla_df, html_bk=True)

# 使用 Pandas 可视化数据
demo_list = np.array([2, 4, 16, 20])
demo_window = 3
pd.rolling_std(demo_list, window=demo_window,
               center=False) * np.sqrt(demo_window)

tsla_df_copy = tsla_df.copy()
# 计算投资回报
tsla_df_copy['return'] = np.log(tsla_df['close'] / tsla_df['close'].shift(1))
# 移动收益标准差
tsla_df_copy['mov_std'] = pd.rolling_std(
    tsla_df_copy['return'], window=20, center=False) * np.sqrt(20)
# 加权移动收益标准差
tsla_df_copy['std_ewm'] = pd.ewmstd(
예제 #18
0
파일: ln30.py 프로젝트: momantang/cobrass
                                            ps,
                                            start=start,
                                            end=end,
                                            n_folds=n_folds,
                                            choice_symbols=choice_symbols)
    ABuProgress.clear_output()
    metrics = AbuMetricsBase.show_general(*abu_result_tuple,
                                          returns_cmp=only_info,
                                          only_info=only_info,
                                          only_show_returns=True)
    return abu_result_tuple, metrics


# 买入策略使用AbuDownUpTrend
buy_factors = [{'class': AbuDownUpTrend}]
# 卖出策略:利润保护止盈策略+风险下跌止损+较大的止盈位
sell_factors = [{
    'stop_loss_n': 1.0,
    'stop_win_n': 3.0,
    'class': AbuFactorAtrNStop
}, {
    'class': AbuFactorPreAtrNStop,
    'pre_atr_n': 1.5
}, {
    'class': AbuFactorCloseAtrNStop,
    'close_atr_n': 1.5
}]
# 开始回测
abu_result_tuple, metrics = run_loo_back(us_choice_symbols, only_info=True)
ABuMarketDrawing.plot_candle_from_order(abu_result_tuple.orders_pd)