Beispiel #1
0
def tasa_implicita(df_futuro, df_spot, fecha_vto):
    """
    Determinación de la tasa implícita al día del vencimiento
    del futuro, considerando el precio del spot
    inputs:
        Cotización del Futuro (pandas series)
        Precio del Spot (pandas series)
        Fecha del día (datetime)
        Fecha del Vto (datetime)
    """

    ohlc_stock = getOHLC(df_futuro)
    ohlc_spot = getOHLC(df_spot)

    ohlc_stock.rename(columns={'close': 'close_LA'}, inplace=True)
    ohlc_spot.rename(columns={'close': 'close_IV'}, inplace=True)

    ohlc_stock.drop(['open', 'high', 'low'], axis=1, inplace=True)
    ohlc_spot.drop(['open', 'high', 'low'], axis=1, inplace=True)

    df = pd.concat([ohlc_stock, ohlc_spot], axis=1, join='inner')
    # df.dropna(inplace=True, axis=0)
    df['base'] = df.close_LA - df.close_IV

    df['dias_vto'] = (fecha_vto - df.index).days + 1

    df['tasa_implicita'] = df.base / df.close_IV * 365 / df.dias_vto

    df.dropna(inplace=True)
    # print(df)
    df = df[['tasa_implicita', 'close_LA']]
    df.rename(columns={'close_LA': 'close'}, inplace=True)
    return df
Beispiel #2
0
def mean_reversion(ticker, period='1min', window=5, start_date=''):
    """
    Mean reversion Strategy.
    Basically follows the moving average, and the standard deviatino of the sotck price, and look if is moment of buy or sell.
    More info in https://medium.com/auquan/mean-reversion-simple-trading-strategies-part-1-a18a87c1196a
    """
    df = utils.DBtools.read_ticker(ticker, start_date=start_date)
    df = df.drop_duplicates('LA_date')
    ohlc = getOHLC(df, 'LA_price', 'LA_size', period)
    ohlc.dropna(inplace=True)

    ohlc['mean'] = ohlc.close.rolling(window=window).mean()
    ohlc['std'] = ohlc.close.rolling(window=window).std()
    ohlc['zscore'] = (ohlc['close'] - ohlc['mean']) / ohlc['std']
    # Sell short if the z-score is > 1
    ohlc.loc[(ohlc.zscore > 1), 'estrategia'] = -1
    # Buy long if the z-score is < -1
    ohlc.loc[(ohlc.zscore < -1), 'estrategia'] = 1
    # Clear positions if the z-score between -.5 and .5
    ohlc.loc[(ohlc.zscore < 0.5) & (ohlc.zscore > -0.5), 'estrategia'] = 0
    ohlc['estrategia'].fillna(method='ffill', inplace=True)

    ohlc['returns'] = ohlc.close.diff() * ohlc.estrategia
    ohlc['Cumulative'] = ohlc.returns.cumsum()

    return ohlc
Beispiel #3
0
def cruce_medias(ticker, period='1min', long_window=10 * 3, short_window=5):
    """
    Estrategia utilizando el cruce de dos medias. Para poder calcular las medias,
    primero debo generar el OHLC en el periodo especificado. A su vez, se caluclan
    las dos medias moviles simples para la ventana long y short. En funcion del cruce
    se determina si comprar o vender
    """
    start = datetime.now()
    df = utils.DBtools.read_ticker(ticker)
    print('Just read the database takes:',
          (datetime.now() - start).total_seconds())
    ##        df.index = pd.to_datetime(df.index)
    df = df[df['Ticker'] == ticker].drop_duplicates('LA_date')
    print('Read the info from database and make a DataFrame takes:,' (
        datetime.now() - start).total_seconds())
    FS = 1.0  #Factor de seguridad = 2%?
    start = datetime.now()

    ohlc = getOHLC(df, period=period)
    ohlc.fillna(method='ffill', inplace=True)
    ohlc = ohlc.between_time('10:00', '17:00')
    print('get the OHLC takes:,' (datetime.now() - start).total_seconds())
    start = datetime.now()
    estrategia = ohlc.copy()
    estrategia['SMA_short'] = ohlc.close.rolling(window=short_window).mean()
    estrategia['SMA_long'] = ohlc.close.rolling(window=long_window).mean()

    estrategia.loc[estrategia['SMA_short'] > estrategia['SMA_long'] * FS,
                   'estrategia'] = 1
    estrategia.loc[estrategia['SMA_short'] < estrategia['SMA_long'] / FS,
                   'estrategia'] = -1
    estrategia.estrategia.fillna(method='ffill', inplace=True)

    estrategia = estrategia.loc[
        estrategia.index > datetime.strptime('19-02-2019', '%d-%m-%Y')]
    position = estrategia.estrategia.iloc[-1]
    print('Calculate the strategy takes:,' (datetime.now() -
                                            start).total_seconds())

    if position == 1:
        price = df['OF_price'].iloc[-1]
        side = 'BUY'
    elif position == -1:
        price = df['BI_price'].iloc[-1]
        side = 'SELL'
    else:
        price = 0
        side = ''
    return position, price, side, estrategia
Beispiel #4
0
def PP(df, ticker):
    """
    Determinación de Soportes y resistencais en función de precio de apertura y cierre. Es lo denominado, Puntos de Pivot en la literatura.
    
    R1 = (P x 2) – L
    S1 = (P x 2) – H
    R2 = P + (H - L) = P + (R1 - S1)
    S2 = P - (H - L) = P - (R1 - S1)

    donde:
    P: Nivel de Pivot
    L: Anterior Low
    H: Anterior High
    R1: Nivel de resistencia 1
    S1: Nivel de soporte 1
    R2: Nivel de resistencia 2
    S2: Nivel de soporte 2
    """
    df = df[df['Ticker'] == ticker].drop_duplicates('LA_date')
    ohlc = getOHLC(df, 'LA_price', 'LA_size')
    ohlc.dropna(inplace=True)
    pp = indicadores.puntos_pivot(ohlc)
    r1 = pp * 2 - ohlc.low.shift(1)
    s1 = pp * 2 - ohlc.high.shift(1)
    r2 = pp + r1 - s1
    s2 = pp - r1 + s1
    indicador = pd.concat([
        pp.rename('pp'),
        r1.rename('r1'),
        s1.rename('s1'),
        r2.rename('r2'),
        s2.rename('s2')
    ],
                          sort=False,
                          axis=1)

    end = datetime.now()
    # print(df.tail())
    # print(indicador.tail())
    # print('Perform the strategy takes ', end-start, 'seconds')
    return indicador
Beispiel #5
0
def stochastic(ticker, period='2min'):
    """
    Compra y venta en funcion del valor del estocastico. Si cruza hacia abajo de 80, es venta, si cruza hacia arriba de 20, es compra.
    """
    df = utils.DBtools.read_ticker(ticker)
    df = df[df['Ticker'] == ticker].drop_duplicates('LA_date')
    ohlc = getOHLC(df, 'LA_price', 'LA_size', period)
    # ohlc.dropna(inplace=True)
    ohlc.drop(['open', 'high', 'low', 'volumen'], axis=1, inplace=True)
    ohlc.fillna(method='ffill', inplace=True)

    stoch = indicadores.stochastic(ohlc, 'close')
    ohlc = pd.concat([ohlc, stoch], axis=1, join_axes=[ohlc.index])

    ohlc.loc[(stoch.d < 20) & (stoch.d.shift(-1) > 20), 'estrategia'] = 1
    ohlc.loc[(stoch.d > 80) & (stoch.d.shift(-1) < 80), 'estrategia'] = -1
    ohlc.fillna(method='ffill', inplace=True)

    ohlc.insert(len(ohlc.columns), 'cum returns',
                ohlc.close.diff() * ohlc.estrategia)

    return ohlc
Beispiel #6
0
def FollowTheVolume(ticker,
                    start_date=datetime.today().strftime('%Y-%m-%d'),
                    period='1min',
                    no_operation_roc=0.005):
    start = datetime.now()
    df = utils.DBtools.read_ticker(ticker, start_date=start_date)
    df = df.drop_duplicates('LA_date')
    # print("get the df from the DB takes ", (datetime.now()-start).total_seconds(), "seconds")
    start = datetime.now()
    try:
        ohlc = getOHLC(df, 'LA_price', 'LA_size', period)
        ohlc.dropna(inplace=True)
        # print("get the OHLC takes ", (datetime.now()-start).total_seconds(), "seconds")
        start = datetime.now()
        ohlc = indicadores.vwap(ohlc,
                                column_price_name='close',
                                column_volume_name='volume')
        # print("get the VWAP takes ", (datetime.now()-start).total_seconds(), "seconds")
        start = datetime.now()
        ohlc = indicadores.ROC(ohlc, column_price_name='VWAP')
        # print("get the ROC takes ", (datetime.now()-start).total_seconds(), "seconds")
        start = datetime.now()

        ohlc.loc[(ohlc.ROC < 0), 'estrategia'] = -1
        ohlc.loc[(ohlc.ROC > 0), 'estrategia'] = 1
        # ohlc.loc[(ohlc.ROC > -no_operation_roc) & (ohlc.ROC < no_operation_roc), 'estrategia'] = 0

        ohlc['estrategia'].fillna(method='ffill', inplace=True)
        # print("get the Strategy takes ", (datetime.now()-start).total_seconds(), "seconds")
        start = datetime.now()

        ohlc['returns'] = ohlc.close.diff() * ohlc.estrategia
        ohlc['Cumulative'] = ohlc.returns.cumsum()
    except:
        ohlc = pd.DataFrame()
    return ohlc
Beispiel #7
0
    ohlc.dropna(inplace=True)
    pp = indicadores.puntos_pivot(ohlc)
    r1 = pp * 2 - ohlc.low.shift(1)
    s1 = pp * 2 - ohlc.high.shift(1)
    r2 = pp + r1 - s1
    s2 = pp - r1 + s1
    indicador = pd.concat([
        pp.rename('pp'),
        r1.rename('r1'),
        s1.rename('s1'),
        r2.rename('r2'),
        s2.rename('s2')
    ],
                          sort=False,
                          axis=1)

    end = datetime.now()
    # print(df.tail())
    # print(indicador.tail())
    # print('Perform the strategy takes ', end-start, 'seconds')
    return indicador


if __name__ == "__main__":
    from finance_tools import getOHLC
    from CSVtools import read_csvData
    df = pd.DataFrame()
    df = read_csvData('TestData.csv')
    ohlc = getOHLC(df)
    stocastico(ohlc)