# -*- coding: utf-8 -*-

import talib
import pandas as pd
import numpy as np


class IndicatorSignal(object):
    def __init__(self, name=None):
        self.name = name

    def get_signal_df(self, ohlc_df):
        pass


class MACDSignal(IndicatorSignal):
    def __init__(self, fastperiod=12, slowperiod=26, signalperiod=9, name=None):
        self.fastperiod = fastperiod
        self.slowperiod = slowperiod
        self.signalperiod = signalperiod
        self.name = name if name is not None else 'MACD(%d,%d,%d)' % (
            fastperiod, slowperiod, signalperiod)

    def get_signal_df(self, ohlc_df):
        macd, signal, hist = talib.MACD(ohlc_df['close'].values,
                                        fastperiod=self.fastperiod,
                                        slowperiod=self.slowperiod,
                                        signalperiod=self.signalperiod)
        df = pd.DataFrame(
            data=np.zeros(ohlc_df.index.size),
            index=ohlc_df.index.copy(),
            columns=['sig']
        )
        for idx in range(1, len(macd)):
            if macd[idx - 1] <= 0 < macd[idx]:
                df.iloc[idx]['sig'] = 1
            elif macd[idx - 1] > 0 >= macd[idx]:
                df.iloc[idx]['sig'] = -1
        return df
