项目2:突破策略

相关的一些辅助函数

In [47]:
import pandas as pd
import numpy as np
import scipy.stats
from colour import Color
import numpy as np
import pandas as pd
import plotly as py
import plotly.graph_objs as go
import plotly.offline as offline_py
offline_py.init_notebook_mode(connected=True)
import project_tests


color_scheme = {
    'index': '#B6B2CF',
    'etf': '#2D3ECF',
    'tracking_error': '#6F91DE',
    'df_header': 'silver',
    'df_value': 'white',
    'df_line': 'silver',
    'heatmap_colorscale': [(0, '#6F91DE'), (0.5, 'grey'), (1, 'red')],
    'background_label': '#9dbdd5',
    'low_value': '#B6B2CF',
    'high_value': '#2D3ECF',
    'y_axis_2_text_color': 'grey',
    'shadow': 'rgba(0, 0, 0, 0.75)',
    'major_line': '#2D3ECF',
    'minor_line': '#B6B2CF',
    'main_line': 'black'}


def generate_config():
    return {'showLink': False, 'displayModeBar': False, 'showAxisRangeEntryBoxes': True}



def _generate_stock_trace(prices):
    return go.Scatter(
        name='Index',
        x=prices.index,
        y=prices,
        line={'color': color_scheme['main_line']})


def _generate_buy_annotations(prices, signal):
    return [{
        'x': index, 'y': price, 'text': 'Long', 'bgcolor': color_scheme['background_label'],
        'ayref': 'y', 'ax': 0, 'ay': 20}
        for index, price in prices[signal == 1].iteritems()]


def _generate_sell_annotations(prices, signal):
    return [{
        'x': index, 'y': price, 'text': 'Short', 'bgcolor': color_scheme['background_label'],
        'ayref': 'y', 'ax': 0, 'ay': 160}
        for index, price in prices[signal == -1].iteritems()]


def _generate_second_tetration_stock(stock_symbol, dates):
    """
    Generate stock that follows the second tetration curve
    :param stock_symbol: Stock Symbol
    :param dates: Dates for ticker
    :return: Stock data
    """
    n_stock_columns = 5
    linear_line = np.linspace(1, 5, len(dates))
    all_noise = ((np.random.rand(n_stock_columns, len(dates)) - 0.5) * 0.01)
    sector_stock = pd.DataFrame({
        'ticker': stock_symbol,
        'date': dates,
        'base_line': np.power(linear_line, linear_line)})

    sector_stock['base_line'] = sector_stock['base_line'] + all_noise[0]*sector_stock['base_line']
    sector_stock['adj_open'] = sector_stock['base_line'] + all_noise[1]*sector_stock['base_line']
    sector_stock['adj_close'] = sector_stock['base_line'] + all_noise[2]*sector_stock['base_line']
    sector_stock['adj_high'] = sector_stock['base_line'] + all_noise[3]*sector_stock['base_line']
    sector_stock['adj_low'] = sector_stock['base_line'] + all_noise[4]*sector_stock['base_line']

    sector_stock['adj_high'] = sector_stock[['adj_high', 'adj_open', 'adj_close']].max(axis=1)
    sector_stock['adj_low'] = sector_stock[['adj_low', 'adj_open', 'adj_close']].min(axis=1)

    return sector_stock.drop(columns='base_line')


def generate_tb_sector(dates):
    """
    Generate TB sector of stocks
    :param dates: Dates that stocks should have market data on
    :return: TB sector stocks
    """
    symbol_length = 6
    stock_names = [
        'kaufmanniana', 'clusiana', 'greigii', 'sylvestris', 'turkestanica', 'linifolia', 'gesneriana',
        'humilis', 'tarda', 'saxatilis', 'dasystemon', 'orphanidea', 'kolpakowskiana', 'praestans',
        'sprengeri', 'bakeri', 'pulchella', 'biflora', 'schrenkii', 'armena', 'vvedenskyi', 'agenensis',
        'altaica', 'urumiensis']

    return [
        _generate_second_tetration_stock(stock_name[:symbol_length].upper(), dates)
        for stock_name in stock_names]


def plot_stock(prices, title):
    config = generate_config()
    layout = go.Layout(title=title)

    stock_trace = _generate_stock_trace(prices)

    offline_py.iplot({'data': [stock_trace], 'layout': layout}, config=config)


def plot_high_low(prices, lookback_high, lookback_low, title):
    config = generate_config()
    layout = go.Layout(title=title)

    stock_trace = _generate_stock_trace(prices)
    high_trace = go.Scatter(
        x=lookback_high.index,
        y=lookback_high,
        name='Column lookback_high',
        line={'color': color_scheme['major_line']})
    low_trace = go.Scatter(
        x=lookback_low.index,
        y=lookback_low,
        name='Column lookback_low',
        line={'color': color_scheme['minor_line']})

    offline_py.iplot({'data': [stock_trace, high_trace, low_trace], 'layout': layout}, config=config)


def plot_signal(price, signal, title):
    config = generate_config()
    buy_annotations = _generate_buy_annotations(price, signal)
    sell_annotations = _generate_sell_annotations(price, signal)
    layout = go.Layout(
        title=title,
        annotations=buy_annotations + sell_annotations)

    stock_trace = _generate_stock_trace(price)

    offline_py.iplot({'data': [stock_trace], 'layout': layout}, config=config)


def plot_lookahead_prices(prices, lookahead_price_list, title):
    config = generate_config()
    layout = go.Layout(title=title)
    colors = Color(color_scheme['low_value'])\
        .range_to(Color(color_scheme['high_value']), len(lookahead_price_list))

    traces = [_generate_stock_trace(prices)]
    for (lookahead_prices, lookahead_days), color in zip(lookahead_price_list, colors):
        traces.append(
            go.Scatter(
                x=lookahead_prices.index,
                y=lookahead_prices,
                name='{} Day Lookahead'.format(lookahead_days),
                line={'color': str(color)}))

    offline_py.iplot({'data': traces, 'layout': layout}, config=config)


def plot_price_returns(prices, lookahead_returns_list, title):
    config = generate_config()
    layout = go.Layout(
        title=title,
        yaxis2={
            'title': 'Returns',
            'titlefont': {'color': color_scheme['y_axis_2_text_color']},
            'tickfont': {'color': color_scheme['y_axis_2_text_color']},
            'overlaying': 'y',
            'side': 'right'})
    colors = Color(color_scheme['low_value'])\
        .range_to(Color(color_scheme['high_value']), len(lookahead_returns_list))

    traces = [_generate_stock_trace(prices)]
    for (lookahead_returns, lookahead_days), color in zip(lookahead_returns_list, colors):
        traces.append(
            go.Scatter(
                x=lookahead_returns.index,
                y=lookahead_returns,
                name='{} Day Lookahead'.format(lookahead_days),
                line={'color': str(color)},
                yaxis='y2'))

    offline_py.iplot({'data': traces, 'layout': layout}, config=config)


def plot_signal_returns(prices, signal_return_list, titles):
    config = generate_config()
    layout = go.Layout(
        yaxis2={
            'title': 'Signal Returns',
            'titlefont': {'color': color_scheme['y_axis_2_text_color']},
            'tickfont': {'color': color_scheme['y_axis_2_text_color']},
            'overlaying': 'y',
            'side': 'right'})
    colors = Color(color_scheme['low_value'])\
        .range_to(Color(color_scheme['high_value']), len(signal_return_list))

    stock_trace = _generate_stock_trace(prices)
    for (signal_return, signal, lookahead_days), color, title in zip(signal_return_list, colors, titles):
        non_zero_signals = signal_return[signal_return != 0]
        signal_return_trace = go.Scatter(
                x=non_zero_signals.index,
                y=non_zero_signals,
                name='{} Day Lookahead'.format(lookahead_days),
                line={'color': str(color)},
                yaxis='y2')

        buy_annotations = _generate_buy_annotations(prices, signal)
        sell_annotations = _generate_sell_annotations(prices, signal)
        layout['title'] = title
        layout['annotations'] = buy_annotations + sell_annotations

        offline_py.iplot({'data': [stock_trace, signal_return_trace], 'layout': layout}, config=config)


def plot_signal_histograms(signal_list, title, subplot_titles):
    assert len(signal_list) == len(subplot_titles)

    signal_series_list = [signal.stack() for signal in signal_list]
    all_values = pd.concat(signal_series_list)
    x_range = [all_values.min(), all_values.max()]
    y_range = [0, 1500]
    config = generate_config()
    colors = Color(color_scheme['low_value']).range_to(Color(color_scheme['high_value']), len(signal_series_list))

    fig = py.tools.make_subplots(rows=1, cols=len(signal_series_list), subplot_titles=subplot_titles, print_grid=False)
    fig['layout'].update(title=title, showlegend=False)

    for series_i, (signal_series, color) in enumerate(zip(signal_series_list, colors), 1):
        filtered_series = signal_series[signal_series != 0].dropna()
        trace = go.Histogram(x=filtered_series, marker={'color': str(color)})
        fig.append_trace(trace, 1, series_i)
        fig['layout']['xaxis{}'.format(series_i)].update(range=x_range)
        fig['layout']['yaxis{}'.format(series_i)].update(range=y_range)

    offline_py.iplot(fig, config=config)


def plot_signal_to_normal_histograms(signal_list, title, subplot_titles):
    assert len(signal_list) == len(subplot_titles)

    signal_series_list = [signal.stack() for signal in signal_list]
    all_values = pd.concat(signal_series_list)
    x_range = [all_values.min(), all_values.max()]
    y_range = [0, 1500]
    config = generate_config()

    fig = py.tools.make_subplots(rows=1, cols=len(signal_series_list), subplot_titles=subplot_titles, print_grid=False)
    fig['layout'].update(title=title)

    for series_i, signal_series in enumerate(signal_series_list, 1):
        filtered_series = signal_series[signal_series != 0].dropna()
        filtered_series_trace = go.Histogram(
            x=filtered_series,
            marker={'color': color_scheme['low_value']},
            name='Signal Return Distribution',
            showlegend=False)
        normal_trace = go.Histogram(
            x=np.random.normal(np.mean(filtered_series), np.std(filtered_series), len(filtered_series)),
            marker={'color': color_scheme['shadow']},
            name='Normal Distribution',
            showlegend=False)
        fig.append_trace(filtered_series_trace, 1, series_i)
        fig.append_trace(normal_trace, 1, series_i)
        fig['layout']['xaxis{}'.format(series_i)].update(range=x_range)
        fig['layout']['yaxis{}'.format(series_i)].update(range=y_range)

    # Show legened
    fig['data'][0]['showlegend'] = True
    fig['data'][1]['showlegend'] = True

    offline_py.iplot(fig, config=config)

数据加载和预处理

In [48]:
df_original = pd.read_csv('./eod-quotemedia.csv', parse_dates=['date'], index_col=False)

# Add TB sector to the market
df = df_original
df = pd.concat([df] + generate_tb_sector(df[df['ticker'] == 'AAPL']['date']), ignore_index=True)

close = df.reset_index().pivot(index='date', columns='ticker', values='adj_close')
high = df.reset_index().pivot(index='date', columns='ticker', values='adj_high')
low = df.reset_index().pivot(index='date', columns='ticker', values='adj_low')

print('Loaded Data')
Loaded Data
In [49]:
close
Out[49]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2013-07-01 29.99418563 16.17609308 81.13821681 53.10917319 34.92447839 50.86319750 31.42538772 64.69409505 46.23500000 39.91336014 ... 27.66879066 35.28892781 76.32080247 40.02387348 22.10666494 25.75338607 45.48038323 71.89882693 27.85858718 29.44789315
2013-07-02 29.65013670 15.81983388 80.72207258 54.31224742 35.42807578 50.69676639 31.27288084 64.71204071 46.03000000 39.86057632 ... 27.54228410 35.05903252 76.60816761 39.96552964 22.08273998 25.61367511 45.40266113 72.93417195 28.03893238 28.57244125
2013-07-03 29.70518453 16.12794994 81.23729877 54.61204262 35.44486235 50.93716689 30.72565028 65.21451912 46.42000000 40.18607651 ... 27.33445191 35.28008569 76.65042719 40.00442554 22.20236479 25.73475794 46.06329899 72.30145844 28.18131017 28.16838652
2013-07-05 30.43456826 16.21460758 81.82188233 54.17338125 35.85613355 51.37173702 31.32670680 66.07591068 47.00000000 40.65233352 ... 27.69589920 35.80177117 77.39419581 40.67537968 22.58516418 26.06075017 46.41304845 73.16424628 29.39626730 29.02459772
2013-07-08 30.52402098 16.31089385 82.95141667 53.86579916 36.66188936 52.03746147 31.76628544 66.82065546 46.62500000 40.25645492 ... 27.98505704 35.20050655 77.96892611 40.64620776 22.48946433 26.22840332 46.95062632 73.89282298 29.57661249 29.76536472
2013-07-09 30.68916447 16.71529618 82.43619048 54.81320389 36.35973093 51.69535307 31.16522893 66.48866080 47.26000000 40.69632003 ... 28.31939579 35.50113886 78.89018496 40.80179133 22.48946433 26.58233774 47.28094525 73.70108798 28.91218282 29.80384612
2013-07-10 31.17771395 16.53235227 81.99032166 54.60295791 36.85493502 52.28710814 31.16522893 66.71298151 47.25000000 41.10979324 ... 27.95794850 36.39419366 78.45068533 40.71427558 22.96796358 26.98284247 47.08340158 74.00785631 28.32368796 29.86156823
2013-07-11 31.45983407 16.72492481 82.00022986 55.45406479 37.08155384 53.72026495 31.85599537 67.47567196 47.99000000 42.22705062 ... 28.50011944 37.00430040 78.83102155 41.01571874 23.23113816 27.03872686 46.54333492 74.93774876 27.84909533 29.74612402
2013-07-12 31.48047700 16.90786872 81.91105609 55.35309481 38.15724076 53.98840397 31.81096287 67.76280247 48.39000000 42.53495620 ... 28.92482002 38.00346072 78.94089646 40.83096325 23.49431274 27.08529718 45.96422730 75.68549560 28.44708204 30.15979909
2013-07-15 31.72819223 17.10044125 82.61453801 55.47379158 37.79303181 53.84971137 31.95506689 68.41781897 48.12000000 42.57894271 ... 29.27723113 38.17146113 78.81411772 40.84068723 23.54216266 27.06666905 46.69299195 76.27027369 28.77929688 30.38106716
2013-07-16 31.59057266 17.28338516 81.62371841 55.83133953 37.10696377 53.88669607 32.15320992 67.55642741 47.48500000 42.68451033 ... 29.04229039 38.27314559 78.85637730 40.86013517 23.27898808 26.61959399 46.56936223 76.81670381 28.06740794 29.97701243
2013-07-17 31.38414330 17.76481650 80.74188897 55.84626440 37.23401341 54.06237335 32.26128793 67.43978064 48.04000000 42.80767257 ... 29.18686931 38.48977769 78.99160796 40.93792696 23.18328823 26.66616431 46.45874617 78.30261578 28.06740794 29.81346647
2013-07-18 31.58369168 17.73593062 81.74261676 56.03418797 37.53893253 53.91443458 32.15320992 67.69101984 48.19000000 42.52615889 ... 29.55735279 40.52346684 79.76918424 41.22964615 23.49431274 26.94558622 46.97929234 78.81069986 28.77929688 29.64992051
2013-07-19 31.79012104 17.55298671 81.45527908 55.15063572 37.70833205 54.37674323 32.30632044 67.49361761 48.07000000 42.20945601 ... 29.71096789 40.54999322 80.43688561 41.24909410 23.20721320 26.81518933 46.90121042 81.16898043 28.99760949 29.09194018
2013-07-22 32.20297975 17.47595770 81.99032166 55.32713852 38.08948096 54.54317435 32.24327493 67.29621538 48.28000000 42.17426681 ... 29.84651063 40.59420386 80.14952046 41.49219343 23.47038778 26.88970184 46.50429396 81.02518181 29.27287321 29.12080123
2013-07-23 31.97590746 17.37967143 81.94078068 54.37713815 37.53046256 53.28569482 33.03584705 66.62325323 48.07000000 42.56134810 ... 29.13265221 40.52346684 80.46224136 41.32688588 23.42253785 26.74067682 45.82758393 81.00601167 28.38063907 28.91877387
2013-07-24 32.17545584 17.81295964 80.78152175 57.17003539 36.96297418 52.49052395 32.82869752 66.14769330 47.80000000 42.42938857 ... 28.73506019 40.24051879 80.28475112 41.15185437 23.51823770 26.62890805 46.49128030 80.56503316 28.53250871 28.76484826
2013-07-25 32.10664605 18.13070432 81.46518728 56.90917464 37.47117273 53.26720248 32.94578204 65.62726924 47.79000000 42.88684829 ... 29.02421802 41.05399445 80.26784729 40.91847901 23.44646282 26.85244558 46.91422407 79.47217195 28.19080202 29.36130999
2013-07-26 31.37726233 18.38104862 81.88133151 57.23233050 37.93702140 54.06237335 33.12591207 65.60932358 47.64000000 42.71969954 ... 29.11457985 40.83294128 80.11571280 40.98654682 23.18328823 26.70342056 48.15052124 80.98684153 28.04842424 29.27472684
2013-07-29 31.19835688 18.51584940 81.57417743 58.11484449 38.16571074 53.98840397 33.08988606 64.93636143 47.17000000 42.66691573 ... 28.92482002 40.38199282 79.47336717 40.93792696 23.08758839 26.50782523 47.83819353 80.16240164 27.71620940 28.94763492
2013-07-30 30.86118893 18.48696352 81.43546269 58.83253602 37.86079161 53.84046520 33.21597708 66.16563896 47.36000000 43.04519972 ... 28.38264907 40.88599404 79.28742502 41.08378656 23.06366342 23.78811863 47.53237266 79.55844670 27.77316051 28.96206545
2013-07-31 30.77861719 18.63139292 81.73270857 58.73000866 38.52144972 53.87744989 32.99081455 66.22844876 47.28000000 43.44107832 ... 28.32843198 41.28388974 79.23671352 41.69639686 23.20721320 23.21996075 47.44778390 80.02819050 28.13385091 28.74031861
2013-08-01 31.68002538 18.66027880 82.66407899 59.26808264 38.32664028 54.36749706 33.17995107 67.16162295 47.70000000 43.93372725 ... 28.97000093 41.69062757 78.37461808 41.71584481 23.70963740 23.46212640 48.08545297 80.97725310 28.61793539 29.07775945
2013-08-02 31.91397865 18.21736196 82.70371177 60.02912118 38.38593011 54.07161953 33.09889256 66.92832940 47.45000000 43.87214613 ... 28.87060292 41.12473146 77.71536862 41.78391262 23.92496206 23.53663891 48.40428750 80.52668616 28.61793539 29.82977047
2013-08-05 31.61121560 18.45807764 82.64426260 60.92591114 37.86926159 54.58015904 32.82869752 66.60530757 47.63000000 43.61702437 ... 28.60855363 41.00978381 77.41109964 41.52136535 24.09243679 23.54595298 48.68408107 80.46916901 28.39962278 30.12864664
2013-08-06 31.70754930 18.21736196 82.41637409 60.38082896 38.01325118 54.23805064 32.51346997 65.72597036 47.39000000 43.47626753 ... 28.34650434 40.50305117 77.30967665 41.40467767 23.85318717 23.68566393 48.15052124 79.56803513 27.88706274 30.01295264
2013-08-07 31.84516887 18.16921883 81.53454465 60.34578796 37.75068193 54.31202002 32.36035945 65.50164964 47.10000000 43.23874037 ... 28.19288924 40.52972131 77.19980174 41.22964615 23.61393755 23.19201856 48.07243931 79.17498438 27.57383161 30.11900548
2013-08-08 31.54928679 18.27513373 80.90042011 60.22638901 38.16571074 55.11643707 32.35135295 65.48370398 47.51000000 43.19475386 ... 28.02120177 40.52083127 77.57168605 41.57970919 23.87711213 23.26653107 48.21558951 79.84604489 28.01994868 30.11900548
2013-08-09 31.80388300 17.90924591 82.40646589 59.36939001 37.86926159 55.00548300 32.32433344 65.97720956 47.18000000 43.10678084 ... 27.86758667 40.27190997 77.20825366 41.39495370 23.99673694 23.26653107 48.41079433 79.15581519 27.99147312 29.80084697
2013-08-12 31.96214550 18.12107570 81.69307578 61.05595360 38.14877079 54.24729681 32.33333995 65.31322023 47.20000000 43.46747023 ... 27.76818866 40.35192038 76.50187303 41.53108932 24.28383649 23.12682011 48.45634212 78.90656401 28.10537535 29.24165929
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
2017-05-19 55.50327007 44.83282860 151.06072036 150.70113045 63.42995100 87.59994036 42.31486674 118.75601310 136.43000000 79.14250576 ... 40.43133035 65.31985198 78.78898294 61.13598414 26.81497802 51.24320268 68.90686651 116.46112494 39.54646594 59.92967369
2017-05-22 55.45382835 45.81435227 146.97179877 151.61679784 63.29454092 87.91434122 42.87370534 120.45421034 138.86000000 79.97056004 ... 40.86051697 66.15263846 79.13518133 62.09836493 26.73836380 51.49936943 69.83126290 116.57989212 39.65494752 59.92967369
2017-05-23 58.00502088 46.26049939 140.27992953 151.42972601 63.68142686 87.62941544 42.82468441 119.90450488 139.52000000 79.84391644 ... 41.31896631 62.67453024 79.41406336 62.65396622 26.62344247 52.19890171 69.74275686 116.59968666 40.76934918 61.04261076
2017-05-24 58.56865644 46.36955757 132.66057320 150.97681525 63.76847620 88.39576754 42.67762162 119.70818149 141.12000000 79.99978549 ... 41.61159355 63.13501218 79.13518133 62.23726525 26.89159225 52.01106475 70.75565928 117.87643393 40.13818363 61.90712437
2017-05-25 58.63787484 47.60885514 131.61341035 151.49864721 64.14569000 89.51582062 43.08939743 120.83704093 142.85000000 80.21410542 ... 42.29439045 64.10496348 78.61588375 62.57459460 26.77667091 51.53652928 70.93267135 118.07437924 40.31569894 62.18535864
2017-05-26 58.84553005 48.32269053 133.79749286 151.24265417 63.89421413 89.40774532 43.83451556 120.63090138 141.89000000 80.67197073 ... 42.23586500 64.51645797 78.42355131 62.22734380 26.81497802 50.82472608 70.89333534 118.00509838 39.89163460 62.21516946
2017-05-30 59.69592756 47.54936885 132.63065426 151.30172949 63.85552554 89.43722040 44.11883696 121.49472426 142.41000000 82.61059193 ... 42.33340741 64.38909063 77.99080333 62.12812929 27.12143491 51.20039999 71.20802347 117.21331713 39.31964082 61.86737662
2017-05-31 59.66626253 47.99551598 133.26892494 150.40575387 63.85552554 90.16427240 44.76591323 122.18185609 141.86000000 83.54580618 ... 42.61628041 65.35904193 77.41380602 63.02105992 27.08312780 51.54641544 71.43420556 117.98530385 39.51688006 61.88725050
2017-06-01 60.05190791 48.63003633 136.72954883 150.81928108 64.52290380 91.51030109 45.19729742 122.98678196 141.38000000 80.08746182 ... 42.54800072 65.30025701 77.60613845 63.55681830 27.19804914 51.84300011 72.60445204 121.40975776 39.99025421 62.24498027
2017-06-02 60.13101466 49.09601221 137.42765739 153.05429719 65.04519983 91.94260228 45.58946486 123.42850956 143.48000000 78.82102586 ... 42.21635651 65.52559923 76.45214383 63.94375491 27.12143491 52.39662482 72.76179611 122.66671050 39.54646594 62.10586314
2017-06-05 59.72559259 49.31412858 135.20368297 151.55772252 65.29667569 91.68715157 45.70711509 124.25306776 143.59000000 76.71679380 ... 41.72864445 65.79013140 77.04837438 63.39807508 26.73836380 52.59434793 72.96831019 122.65681324 39.90149656 62.27479108
2017-06-06 59.42894229 49.31412858 130.94522072 152.06970859 65.64487304 90.08567218 45.45220625 124.00766354 143.03000000 78.03193884 ... 41.48478841 66.24081585 78.09658617 63.05082428 26.81497802 52.09015400 73.08631824 122.89434761 39.70425733 62.58283617
2017-06-07 59.95302448 50.42453920 130.26705812 152.97553010 66.49602213 90.32147283 45.64828997 124.22361925 143.62000000 79.18147302 ... 41.45552569 66.49555053 77.80808751 63.10043153 26.96820647 52.85138798 73.02731422 123.07249839 39.90149656 62.86107043
2017-06-08 59.47838401 50.98965889 125.57975776 152.60138644 66.50569428 89.96777186 45.80515695 123.85060483 142.63000000 80.75863709 ... 41.18240693 66.69150029 77.52920548 62.95160976 26.81497802 52.97002185 72.74212810 123.88407418 40.81865898 62.18535864
2017-06-09 58.54887976 49.83959075 128.01316475 146.68400898 67.38585980 90.48849829 46.36399555 123.50703891 138.05000000 76.99695384 ... 41.52380538 64.07557102 78.98131538 62.84247379 26.58513535 53.35558192 71.88656975 123.72571793 41.75554533 62.19529558
2017-06-12 58.33133621 49.05635469 130.59616644 143.17887358 67.25044972 90.74394899 46.24634532 123.97821503 137.25000000 78.11370356 ... 41.13363573 62.92926493 79.75064513 62.25710816 27.04482069 53.40501269 70.71632326 123.71582066 42.33740107 61.45996216
2017-06-13 58.61809816 49.02661155 131.27432905 144.33084223 67.38585980 91.37275071 46.53066671 124.73406004 139.09000000 79.57331502 ... 41.54331386 63.46812677 79.77949499 62.78294509 26.85328513 53.17763111 71.46370757 124.18099215 42.53464030 61.67360633
2017-06-14 58.71698159 48.96712526 130.23713918 142.92288054 68.20799244 92.25700314 46.70714206 124.91075109 138.25000000 79.28922957 ... 41.97472897 63.56610164 78.92361565 63.22941040 26.54682824 53.04911109 71.82756572 124.30965660 42.63325991 61.94235833
2017-06-15 58.54887976 48.68952261 130.79562603 142.06628846 68.28536963 92.77772957 47.17774299 124.69479537 137.52000000 78.12349961 ... 42.63165652 63.54650667 79.10633146 62.81270944 26.61386569 53.34569576 71.40470355 124.54719098 42.27822930 62.10161877
2017-06-16 58.84553005 48.37226243 129.80830106 140.07741950 68.72061632 90.91097444 47.26598066 125.21505233 137.84000000 78.40758506 ... 43.18073029 63.42893681 80.28917595 63.19964605 27.29381692 53.43467116 71.57188162 124.62636910 42.49519245 62.26087921
2017-06-19 59.87391774 49.23481354 129.24981421 144.08469508 69.00110863 92.10962773 47.93266531 125.42119188 140.35000000 78.73085471 ... 43.23955963 64.56544541 79.58716256 63.47744669 27.57154347 53.55330503 72.70279208 125.78434918 42.76146542 62.73866054
2017-06-20 59.65637419 47.61876952 123.24608056 142.77519225 68.88504285 91.61837639 47.81501508 124.20398692 140.91000000 77.58471685 ... 43.33760851 63.93840619 79.15441457 62.85239525 27.13101169 53.26660652 72.68312408 125.91301364 42.36698695 62.70879921
2017-06-21 59.12240366 48.01534474 119.84529455 143.62193844 69.00110863 93.94690777 47.61893136 124.77332472 144.24000000 78.34880876 ... 43.15131563 64.78099015 78.31776847 63.26909621 26.70005669 52.93047722 73.16499028 127.43719255 41.74568337 62.70879921
2017-06-22 59.93324780 48.55072128 120.43399427 143.38563718 70.78078399 94.68378480 48.30522438 119.83579169 143.69000000 79.66147947 ... 42.42575385 65.23167459 77.97157008 63.32862492 26.78624769 53.23694805 73.30266633 128.29986262 41.71609749 63.21644187
2017-06-23 59.10262697 48.21363235 119.47610998 144.02561977 70.25848796 94.14340831 48.11894484 120.48365885 145.41000000 79.88678863 ... 42.56302230 66.16243594 78.48125104 63.33854637 27.23635625 53.71148352 73.57801845 128.00239018 41.35120491 62.48981610
2017-06-26 58.57854478 48.36234805 121.52159207 143.57270901 70.35520945 94.31043377 47.95227368 120.09101209 144.96000000 78.92677572 ... 42.76892496 65.99587865 78.12543603 63.56673975 27.95461459 54.05749897 73.49934641 127.97264293 41.75554533 62.43009343
2017-06-27 58.22256443 48.08474540 121.69121741 141.51491885 70.01668424 93.85848253 47.71697322 119.94376955 142.54000000 76.54633554 ... 43.14151074 63.78164638 78.00041995 63.92391201 27.75350225 53.87954816 72.74212810 127.16946735 41.95278457 62.46990854
2017-06-28 58.73675827 48.82832394 116.45278767 143.58255490 70.52930812 94.69360982 47.53069368 121.46527575 143.81000000 77.58471685 ... 43.30819385 64.67321778 78.40431807 64.82428373 28.28980181 54.34419748 72.91914017 127.42727680 42.37684891 62.65903032
2017-06-29 58.27398382 49.19515602 115.79424221 141.46568942 70.10373358 94.08445815 47.77579833 120.72906307 141.24000000 76.15449354 ... 43.27877918 62.88027749 77.60613845 64.10898129 28.12560699 54.27499439 72.23075989 126.81250043 43.38276899 62.21111032
2017-06-30 58.77942143 49.88916265 116.33305213 141.80044954 70.13275003 92.87597984 47.65814810 121.40637874 141.44000000 76.21326984 ... 42.94541296 63.01744232 77.63498832 64.41695873 27.74892476 54.79896064 72.53561401 127.31820357 43.30387330 62.09166499

1009 rows × 519 columns

In [50]:
apple_ticker = 'AAPL'
plot_stock(close[apple_ticker], '{} Stock'.format(apple_ticker))

计算一个活动窗口内的最高价和最低价

In [51]:
def get_high_lows_lookback(high, low, lookback_days):
    """
    Get the highs and lows in a lookback window.
    
    Parameters
    ----------
    high : DataFrame
        High price for each ticker and date
    low : DataFrame
        Low price for each ticker and date
    lookback_days : int
        The number of days to look back
    
    Returns
    -------
    lookback_high : DataFrame
        Lookback high price for each ticker and date
    lookback_low : DataFrame
        Lookback low price for each ticker and date
    """
    #TODO: Implement function
    #往前移动1行是为了不包含当天的值
    rolling_max_high=high.shift(1).rolling(lookback_days).max()
    rolling_min_low=low.shift(1).rolling(lookback_days).min()

    return rolling_max_high, rolling_min_low

project_tests.test_get_high_lows_lookback(get_high_lows_lookback)
Tests Passed
In [52]:
lookback_days = 50
lookback_high, lookback_low = get_high_lows_lookback(high, low, lookback_days)
plot_high_low(
    close[apple_ticker],
    lookback_high[apple_ticker],
    lookback_low[apple_ticker],
    'High and Low of {} Stock'.format(apple_ticker))

计算多空信号

Signal Condition
-1 Low > Close Price
1 High < Close Price
0 Otherwise
In [54]:
def get_long_short(close, lookback_high, lookback_low):
    """
    Generate the signals long, short, and do nothing.
    
    Parameters
    ----------
    close : DataFrame
        Close price for each ticker and date
    lookback_high : DataFrame
        Lookback high price for each ticker and date
    lookback_low : DataFrame
        Lookback low price for each ticker and date
    
    Returns
    -------
    long_short : DataFrame
        The long, short, and do nothing signals for each ticker and date
    """
    #TODO: Implement function
    long_signals = (close > lookback_high).astype(np.int)
    short_signas = (close < lookback_low).astype(np.int) * -1
    long_short = long_signals + short_signas
    
    return long_short

project_tests.test_get_long_short(get_long_short)
Tests Passed
In [55]:
signal = get_long_short(close, lookback_high, lookback_low)
plot_signal(
    close[apple_ticker],
    signal[apple_ticker],
    'Long and Short of {} Stock'.format(apple_ticker))

信号过滤

前面的步骤有许多重复的信号!如果我们已经做空一个股票,再有一个做空该股票的信号对策略没有帮助。对于做多也是一样的方法。

实现filter_signals过滤掉在lookahead_days天内重复的做多或者做空信号。如果前面的信号是一样的,改为0。例如,假设你有下面的股票时间序列

[1, 0, 1, 0, 1, 0, -1, -1]

运行lookahead_days参数为3的filter_signals应该返回下面的序列

[1, 0, 0, 0, 1, 0, -1, 0]

In [56]:
def clear_signals(signals, window_size):
    """
    Clear out signals in a Series of just long or short signals.
    
    Remove the number of signals down to 1 within the window size time period.
    
    Parameters
    ----------
    signals : Pandas Series
        The long, short, or do nothing signals
    window_size : int
        The number of days to have a single signal       
    
    Returns
    -------
    signals : Pandas Series
        Signals with the signals removed from the window size
    """
    # Start with buffer of window size
    # This handles the edge case of calculating past_signal in the beginning
    clean_signals = [0]*window_size
    
    for signal_i, current_signal in enumerate(signals):
        # Check if there was a signal in the past window_size of days
        has_past_signal = bool(sum(clean_signals[signal_i:signal_i+window_size]))
        # Use the current signal if there's no past signal, else 0/False
        clean_signals.append(not has_past_signal and current_signal)
        
    # Remove buffer
    clean_signals = clean_signals[window_size:]

    # Return the signals as a Series of Ints
    return pd.Series(np.array(clean_signals).astype(np.int), signals.index)


def filter_signals(signal, lookahead_days):
    """
    Filter out signals in a DataFrame.
    
    Parameters
    ----------
    signal : DataFrame
        The long, short, and do nothing signals for each ticker and date
    lookahead_days : int
        The number of days to look ahead
    
    Returns
    -------
    filtered_signal : DataFrame
        The filtered long, short, and do nothing signals for each ticker and date
    """
    
    #TODO: Implement function
    f_signal=signal.copy()
    for sector,row in (signal.iteritems()):
        s=row.copy()
        l=row.copy()
        s[s > 0]=0
        l[l < 0]=0
        f_signal[sector]=clear_signals(s,lookahead_days) + clear_signals(l,lookahead_days)
    
    return f_signal

project_tests.test_filter_signals(filter_signals)
Tests Passed
In [57]:
signal_5 = filter_signals(signal, 5)
signal_10 = filter_signals(signal, 10)
signal_20 = filter_signals(signal, 20)
for signal_data, signal_days in [(signal_5, 5), (signal_10, 10), (signal_20, 20)]:
    plot_signal(
        close[apple_ticker],
        signal_data[apple_ticker],
        'Long and Short of {} Stock with {} day signal window'.format(apple_ticker, signal_days))

计算未来的收盘价

In [58]:
def get_lookahead_prices(close, lookahead_days):
    """
    Get the lookahead prices for `lookahead_days` number of days.
    
    Parameters
    ----------
    close : DataFrame
        Close price for each ticker and date
    lookahead_days : int
        The number of days to look ahead
    
    Returns
    -------
    lookahead_prices : DataFrame
        The lookahead prices for each ticker and date
    """
    #TODO: Implement function
    
    return close.shift(-1*lookahead_days)

project_tests.test_get_lookahead_prices(get_lookahead_prices)
Tests Passed
In [59]:
lookahead_5 = get_lookahead_prices(close, 5)
lookahead_10 = get_lookahead_prices(close, 10)
lookahead_20 = get_lookahead_prices(close, 20)
plot_lookahead_prices(
    close[apple_ticker].iloc[150:250],
    [
        (lookahead_5[apple_ticker].iloc[150:250], 5),
        (lookahead_10[apple_ticker].iloc[150:250], 10),
        (lookahead_20[apple_ticker].iloc[150:250], 20)],
    '5, 10, and 20 day Lookahead Prices for Slice of {} Stock'.format(apple_ticker))

计算未来对数收益

In [60]:
def get_return_lookahead(close, lookahead_prices):
    """
    Calculate the log returns from the lookahead days to the signal day.
    
    Parameters
    ----------
    close : DataFrame
        Close price for each ticker and date
    lookahead_prices : DataFrame
        The lookahead prices for each ticker and date
    
    Returns
    -------
    lookahead_returns : DataFrame
        The lookahead log returns for each ticker and date
    """
    #TODO: Implement function
    return  np.log(lookahead_prices) - np.log(close)

project_tests.test_get_return_lookahead(get_return_lookahead)
Tests Passed
In [61]:
price_return_5 = get_return_lookahead(close, lookahead_5)
price_return_10 = get_return_lookahead(close, lookahead_10)
price_return_20 = get_return_lookahead(close, lookahead_20)
plot_price_returns(
    close[apple_ticker].iloc[150:250],
    [
        (price_return_5[apple_ticker].iloc[150:250], 5),
        (price_return_10[apple_ticker].iloc[150:250], 10),
        (price_return_20[apple_ticker].iloc[150:250], 20)],
    '5, 10, and 20 day Lookahead Returns for Slice {} Stock'.format(apple_ticker))

计算信号收益

In [62]:
def get_signal_return(signal, lookahead_returns):
    """
    Compute the signal returns.
    
    Parameters
    ----------
    signal : DataFrame
        The long, short, and do nothing signals for each ticker and date
    lookahead_returns : DataFrame
        The lookahead log returns for each ticker and date
    
    Returns
    -------
    signal_return : DataFrame
        Signal returns for each ticker and date
    """
    #TODO: Implement function
    
    return signal*lookahead_returns

project_tests.test_get_signal_return(get_signal_return)
Tests Passed
In [63]:
title_string = '{} day LookaheadSignal Returns for {} Stock'
signal_return_5 = get_signal_return(signal_5, price_return_5)
signal_return_10 = get_signal_return(signal_10, price_return_10)
signal_return_20 = get_signal_return(signal_20, price_return_20)
plot_signal_returns(
    close[apple_ticker],
    [
        (signal_return_5[apple_ticker], signal_5[apple_ticker], 5),
        (signal_return_10[apple_ticker], signal_10[apple_ticker], 10),
        (signal_return_20[apple_ticker], signal_20[apple_ticker], 20)],
    [title_string.format(5, apple_ticker), title_string.format(10, apple_ticker), title_string.format(20, apple_ticker)])

显著性检验

In [66]:
# plot_signal_histograms(
#     [signal_return_5, signal_return_10, signal_return_20],
#     'Signal Return',
#     ('5 Days', '10 Days', '20 Days'))
plot_signal_histograms(
    [signal_return_5, signal_return_10],
    'Signal Return',
    ('5 Days', '10 Days'))
In [72]:
plot_signal_histograms(
    [ signal_return_10, signal_return_20],
    'Signal Return',
    ( '10 Days', '20 Days'))

异常点

我们发现10天和20天的柱形图有异常点。为了更好地可视化异常点,我们比较5天、10天和20天的信号收益和相同方差与均值的正态分布

In [75]:
plot_signal_to_normal_histograms(
    [signal_return_5,],
    'Signal Return',
    ('5 Days',))
In [76]:
plot_signal_to_normal_histograms(
    [signal_return_10,],
    'Signal Return',
    ('10 Days',))
In [77]:
plot_signal_to_normal_histograms(
    [signal_return_20,],
    'Signal Return',
    ('20 Days',))

Kolmogorov-Smirnov 检测

In [81]:
# Filter out returns that don't have a long or short signal.
long_short_signal_returns_5 = signal_return_5[signal_5 != 0].stack()
long_short_signal_returns_10 = signal_return_10[signal_10 != 0].stack()
long_short_signal_returns_20 = signal_return_20[signal_20 != 0].stack()

# Get just ticker and signal return
long_short_signal_returns_5 = long_short_signal_returns_5.reset_index().iloc[:, [1,2]]
long_short_signal_returns_5.columns = ['ticker', 'signal_return']
long_short_signal_returns_10 = long_short_signal_returns_10.reset_index().iloc[:, [1,2]]
long_short_signal_returns_10.columns = ['ticker', 'signal_return']
long_short_signal_returns_20 = long_short_signal_returns_20.reset_index().iloc[:, [1,2]]
long_short_signal_returns_20.columns = ['ticker', 'signal_return']

# View some of the data
long_short_signal_returns_5.head(10)
Out[81]:
ticker signal_return
0 A 0.00732604
1 ABC 0.01639650
2 ADP 0.00981520
3 AGENEN 0.02199704
4 AKAM 0.04400495
5 ALGN 0.01545561
6 ALTAIC 0.01441441
7 APC 0.00305859
8 ARMENA 0.02007566
9 BA 0.08061297

下面实现函数calculate_kstest计算每只股票的收益与正态分布之间的Kolmogorov-Smirnov test (KS test)。检查每只股票收益与正态分布之间的ks检测。使用scipy.stats.kstest执行KS检测,当计算信号收益的标准差时记得设置delta的自由度为0。

In [83]:
from scipy.stats import kstest


def calculate_kstest(long_short_signal_returns):
    """
    Calculate the KS-Test against the signal returns with a long or short signal.
    
    Parameters
    ----------
    long_short_signal_returns : DataFrame
        The signal returns which have a signal.
        This DataFrame contains two columns, "ticker" and "signal_return"
    
    Returns
    -------
    ks_values : Pandas Series
        KS static for all the tickers
    p_values : Pandas Series
        P value for all the tickers
    """
    #TODO: Implement function
    ks_dict={}
    p_dict={}
    m=long_short_signal_returns.mean()
    std=long_short_signal_returns.std(ddof=0)
    for signal_return in long_short_signal_returns.groupby('ticker'):
        value=signal_return[1]['signal_return'].values
        ks,p=kstest(value, 'norm', args=(m, std))
        ks_dict[signal_return[0]]=ks
        p_dict[signal_return[0]]=p
    return pd.Series(ks_dict),pd.Series(p_dict)


project_tests.test_calculate_kstest(calculate_kstest)
Tests Passed
In [84]:
ks_values_5, p_values_5 = calculate_kstest(long_short_signal_returns_5)
ks_values_10, p_values_10 = calculate_kstest(long_short_signal_returns_10)
ks_values_20, p_values_20 = calculate_kstest(long_short_signal_returns_20)

print('ks_values_5')
print(ks_values_5.head(10))
print('p_values_5')
print(p_values_5.head(10))
ks_values_5
A      0.17234540
AAL    0.10739498
AAP    0.19716718
AAPL   0.15559839
ABBV   0.16838085
ABC    0.21414568
ABT    0.21394736
ACN    0.28243369
ADBE   0.24289681
ADI    0.19450481
dtype: float64
p_values_5
A      0.18607276
AAL    0.72502558
AAP    0.04467211
AAPL   0.24751419
ABBV   0.24554352
ABC    0.02730262
ABT    0.04793981
ACN    0.00580286
ADBE   0.00903674
ADI    0.09823282
dtype: float64

找出异常点

根据ks和p values的结果,我们可以找出那只股票是异常的。实现find_outliers函数找出下面的异常点

  • Symbols that pass the null hypothesis with a p-value less than pvalue_threshold.
  • Symbols that with a KS value above ks_threshold.
In [85]:
def find_outliers(ks_values, p_values, ks_threshold, pvalue_threshold=0.05):
    """
    Find outlying symbols using KS values and P-values
    
    Parameters
    ----------
    ks_values : Pandas Series
        KS static for all the tickers
    p_values : Pandas Series
        P value for all the tickers
    ks_threshold : float
        The threshold for the KS statistic
    pvalue_threshold : float
        The threshold for the p-value
    
    Returns
    -------
    outliers : set of str
        Symbols that are outliers
    """
    #TODO: Implement function
    ks=set(ks_values[ks_values > ks_threshold].index)
    p=set(p_values[p_values < pvalue_threshold].index)
    return ks & p


project_tests.test_find_outliers(find_outliers)
Tests Passed
In [86]:
ks_threshold = 0.8
outliers_5 = find_outliers(ks_values_5, p_values_5, ks_threshold)
outliers_10 = find_outliers(ks_values_10, p_values_10, ks_threshold)
outliers_20 = find_outliers(ks_values_20, p_values_20, ks_threshold)

outlier_tickers = outliers_5.union(outliers_10).union(outliers_20)
print('{} Outliers Found:\n{}'.format(len(outlier_tickers), ', '.join(list(outlier_tickers))))
24 Outliers Found:
ARMENA, LINIFO, PRAEST, CLUSIA, GREIGI, PULCHE, KAUFMA, TURKES, SYLVES, HUMILI, ORPHAN, VVEDEN, URUMIE, KOLPAK, AGENEN, BAKERI, SCHREN, BIFLOR, SPRENG, SAXATI, TARDA, ALTAIC, GESNER, DASYST

显示没有异常点的显著性

In [91]:
good_tickers = list(set(close.columns) - outlier_tickers)
In [88]:
plot_signal_to_normal_histograms(
    [signal_return_5[good_tickers],],
    'Signal Return Without Outliers',
    ('5 Days',))
In [89]:
plot_signal_to_normal_histograms(
    [signal_return_10[good_tickers],],
    'Signal Return Without Outliers',
    ('10 Days',))
In [90]:
plot_signal_to_normal_histograms(
    [signal_return_20[good_tickers],],
    'Signal Return Without Outliers',
    ('20 Days',))
In [ ]: