コード例 #1
0
ファイル: views.py プロジェクト: kpadilha/zecontinha
    def get_context_data(self, **kwargs):
        context = super(PairStatsDetailView, self).get_context_data(**kwargs)
        if hasattr(self, 'form'):
            pvalue = self.form.cleaned_data['pvalue']
            zscore = self.form.cleaned_data['zscore']
            periodo = self.form.cleaned_data['periodo']

            beta_plot = cointegration.get_beta_plot(
                context['object'].beta_rotation)

            context['pvalue'] = float(pvalue)
            context['zscore'] = float(zscore)
            context['beta_plot'] = beta_plot.decode("utf-8")
            context['period'] = periodo

            try:
                periodo = int(periodo)
                ativo_x = self.kwargs['x']
                ativo_y = self.kwargs['y']
                _x = Quotes.objects.get(ticker=ativo_x).get_series()[-periodo:]
                _y = Quotes.objects.get(ticker=ativo_y).get_series()[-periodo:]
                series_x, series_y = cointegration.clean_timeseries(_x, _y)
                plot_context = cointegration.get_plot_context(
                    series_x, series_y, ativo_x, ativo_y)
            except Exception as e:
                print(e)
                plot_context = {'resultados': False}

            context.update(plot_context)

        return context
コード例 #2
0
ファイル: b3_calc.py プロジェクト: vitorpq/zecontinha
def producer(idx, pair):

    _x = market_data[('Close', pair[0])]
    _y = market_data[('Close', pair[1])]
    series_x, series_y = clean_timeseries(_x, _y)

    obj_pair = create_pairstats(pair,
                                'BOVESPA',
                                series_x=series_x,
                                series_y=series_y)
    print(idx, pair)

    try:
        beta_list = beta_rotation(series_x=series_x, series_y=series_y)
        obj_pair.beta_rotation = beta_list
    except MissingDataError:
        print('FAIL - MissingDataError - Beta')
        #raise

    for periodo in PERIODOS_CALCULO:
        slice_x = series_x[-periodo:]
        slice_y = series_y[-periodo:]
        try:
            test_params = coint_model(slice_x, slice_y)
            obj_data = create_cointparams(True, test_params)
            obj_pair.success = True
        except MissingDataError:
            obj_data = create_cointparams(False, test_params)
            print('FAIL - MissingDataError - OLS ADF', periodo)
            #raise

        obj_pair.model_params[periodo] = model_to_dict(obj_data)

    return copy.deepcopy(obj_pair)
コード例 #3
0
ファイル: my_backtest.py プロジェクト: vitorpq/zecontinha
def calcula_modelo(refdate, pair, market='BINANCE'):
    def create_pairstats(pair,
                         market,
                         series_x=pd.Series([]),
                         series_y=pd.Series([])):

        obj = PairStats(
            pair=" ".join(pair),
            market=market,
            refdate=refdate,
            ticker_x=pair[0],
            ticker_y=pair[1],
        )

        if not series_x.empty:
            obj.x_quote = series_x.iloc[-1]

        if not series_y.empty:
            obj.y_quote = series_y.iloc[-1]

        return obj

    df = qsquotes.get(ticker=pair[0]).get_series()
    df2 = df[df.index < refdate]
    _x = df2[df2.index > refdate - timedelta(days=365)]

    df = qsquotes.get(ticker=pair[1]).get_series()
    df2 = df[df.index < refdate]
    _y = df2[df2.index > refdate - timedelta(days=365)]
    series_x, series_y = clean_timeseries(_x, _y)

    model_params = {}
    obj_pair = create_pairstats(pair,
                                market,
                                series_x=series_x,
                                series_y=series_y)
    # Valor esperado: 690
    #print(refdate, pair, 'len_X', len(series_x), 'len_Y', len(series_y))
    #print(refdate, pair)

    for periodo in PERIODOS_CALCULO:
        obj_data = {}
        slice_x = series_x[-periodo:]
        slice_y = series_y[-periodo:]

        try:
            test_params = coint_model(slice_x, slice_y)
            obj_data = create_cointparams(True, test_params)
            obj_pair.success = True
        except MissingDataError:
            obj_data = create_cointparams(False, test_params)
            print('FAIL - MissingDataError - OLS ADF', periodo)
            #raise

        model_params[periodo] = copy.deepcopy(model_to_dict(obj_data))

    obj_pair.model_params = model_params
    return copy.deepcopy(obj_pair)
コード例 #4
0
def get_plot(x_ticker, y_ticker):
    from dashboard.models import PairStats, CointParams, Quotes
    from coint.cointegration import fp_savefig, _get_residuals_plot
    from coint.cointegration import coint_model, clean_timeseries

    _x = Quotes.objects.get(ticker=x_ticker).get_series()
    _y = Quotes.objects.get(ticker=y_ticker).get_series()
    series_x, series_y = clean_timeseries(_x, _y)

    r = coint_model(series_x[-120:], series_y[-120:])
    return fp_savefig(_get_residuals_plot(r['OLS']))
コード例 #5
0
    def init(self):
        Close = self.data.Close
        self.ma1 = self.I(SMA, Close, 10)
        self.ma2 = self.I(SMA, Close, 20)

    def next(self):
        if crossover(self.ma1, self.ma2):
            self.buy()
        elif crossover(self.ma2, self.ma1):
            self.sell()


if __name__ == '__main__':

    Quotes.objects.filter(market='BINANCE').delete()
    download_hquotes_binance()

    _x = Quotes.objects.get(ticker='BTCUSDT').get_series()
    _y = Quotes.objects.get(ticker='LTCUSDT').get_series()
    series_x, series_y = clean_timeseries(_x, _y)
    df = pd.DataFrame()

    df['BTCUSDT'] = series_x
    df['LTCUSDT'] = series_y

    from IPython import embed
    embed()
    bt = Backtest(df, PairTradingCointegration, cash=10000, commission=.002)
    bt.run()
    bt.plot()