示例#1
0
文件: momentum.py 项目: macsrc/ta
 def setUpClass(cls):
     cls._df = pd.read_csv(cls._filename, sep=',')
     cls._params = dict(high=cls._df['High'],
                        low=cls._df['Low'],
                        close=cls._df['Close'],
                        s=7,
                        m=14,
                        len=28,
                        ws=4.0,
                        wm=2.0,
                        wl=1.0,
                        fillna=False)
     cls._indicator = UltimateOscillator(**cls._params)
示例#2
0
 def setUpClass(cls):
     cls._df = pd.read_csv(cls._filename, sep=",")
     cls._params = dict(
         high=cls._df["High"],
         low=cls._df["Low"],
         close=cls._df["Close"],
         window1=7,
         window2=14,
         window3=28,
         weight1=4.0,
         weight2=2.0,
         weight3=1.0,
         fillna=False,
     )
     cls._indicator = UltimateOscillator(**cls._params)
示例#3
0
文件: momentum.py 项目: venkiiee/ta
class TestUltimateOscillator(unittest.TestCase):
    """
    https://school.stockcharts.com/doku.php?id=technical_indicators:ultimate_oscillator
    """

    _filename = 'ta/tests/data/cs-ultosc.csv'

    def setUp(self):
        self._df = pd.read_csv(self._filename, sep=',')
        self._indicator = UltimateOscillator(
            high=self._df['High'], low=self._df['Low'], close=self._df['Close'],
            s=7, m=14, len=28, ws=4.0, wm=2.0, wl=1.0, fillna=False)

    def tearDown(self):
        del(self._df)

    def test_uo(self):
        target = 'Ult_Osc'
        result = self._indicator.uo()
        pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False)
示例#4
0
def get_stock_predictions():
    start = time.time()
    ticker = request.args.get('ticker')
    date = -1

    np.random.seed(312)

    try:
        

        df = stocks[ticker].copy()
        df['return'] = df['PRC'].pct_change()
        df.drop( columns = ['COMNAM'], inplace = True)
        df.set_index('date', inplace=True, drop=True)
        df['1_day_return'] = df['return'].shift(-1)
        df['1_day_return'] = np.where(df['1_day_return'] > 0, 1, 0)

        ewma = pd.Series.ewm

        df['Fast_Exp_Moving_Avg'] = df['PRC'].transform(lambda x: ewma(x, span = 12).mean())
        df['Slow_Exp_Moving_Avg'] = df['PRC'].transform(lambda x: ewma(x, span = 26).mean())
        df['Momentum_Factor'] = df['Fast_Exp_Moving_Avg']/df['Slow_Exp_Moving_Avg']

        df['Moving_Avg'] = df['PRC'].transform(lambda x: x.rolling(window=20).mean())
        df['Moving_Std_Deviation'] = df['PRC'].transform(lambda x: x.rolling(window=20).std())  
        
        df['Ultimate_Oscillator'] = UltimateOscillator(df['ASKHI'], df['BIDLO'], df['PRC'], fillna = True).uo()
        df['RSI_Indicator'] = RSIIndicator(df['PRC'], 14, False).rsi()
        df['Stochastic_Oscillator'] = StochasticOscillator(df['ASKHI'], df['BIDLO'], df['PRC'], 14, 3, True).stoch()

        # print("3")
        n_fast = 12
        n_slow = 26
        df['MACD'] = df['Slow_Exp_Moving_Avg'] - df['Fast_Exp_Moving_Avg']

        # Bollinger Bands
        df['BollingerB_UP'] =  df['Moving_Avg'] + df['Moving_Std_Deviation']*2
        df['BollingerB_DOWN'] = df['Moving_Avg'] - df['Moving_Std_Deviation']*2

        if stocks_industry.get(ticker) != None:
            industry = stocks_industry.get(ticker).lower().replace(" ", "_")

            industry_df = pd.read_csv(f'../database/industry_info/{industry}_returns.csv')
            industry_df.set_index('date', inplace=True, drop=True)
            df['avg_industry_return'] = industry_df['avg_return']

        df.dropna(inplace = True)
        X = df[df.columns[~df.columns.isin(['1_day_return','TICKER'])]]
        y = df.loc[:, '1_day_return']

    except:
        return jsonify({})

    xgb = XGBClassifier(random_state=0, seed = 312)

    xgb.fit(X.iloc[:-1], y.iloc[:-1])

    predict_for = pd.DataFrame(X.iloc[date]).T
    print(predict_for)

    # print(xgb.predict(X))
    answer = xgb.predict_proba(predict_for)[0]
    prediction = xgb.predict(predict_for)[0]
    confidence = max(answer) * 100

    feature_scores = xgb._Booster.get_score()
    
    descriptors = {'OPENPRC': 'The open price', 
               'SHROUT': 'The number of shares outstanding', 
               'Moving_Avg': 'The average price of the stock over a rolling window of 20 days', 
               'Ultimate_Oscillator': 'Larry Williams’ (1976) signal, a momentum oscillator designed to capture momentum across three different timeframes.',
               'VOL': 'The volume traded today',
               'Stochastic_Oscillator': 'Developed in the late 1950s by George Lane. The stochastic oscillator presents the location of the closing price of a stock in relation to the high and low range of the price of a stock over a period of time, typically a 14-day period.',
               'BIDLO': 'The lowest bid price today',
               'ASKHI': 'The highest asking price today',
               'Slow_Exp_Moving_Avg': 'This is a first-order infinite impulse response filter that applies weighting factors which decrease exponentially. Basically, a fancy moving average.',
               'return': 'The return of the stock today, i.e. perentage change from the price yesterday to the price today',
               'RSI_Indicator': 'Compares the magnitude of recent gains and losses over a specified time period to measure speed and change of price movements of a security. It is primarily used to attempt to identify overbought or oversold conditions in the trading of an asset.',
               'BollingerB_DOWN': 'Developed by John Bollinger, Bollinger Bands® are volatility bands placed above and below a moving average. Volatility is based on the standard deviation, which changes as volatility increases and decreases',
               'BollingerB_UP': 'Developed by John Bollinger, Bollinger Bands® are volatility bands placed above and below a moving average. Volatility is based on the standard deviation, which changes as volatility increases and decreases',
               'Momentum_Factor': 'Simple Momentum of the stock',
               'PRC': 'The closing price of the stock',
               'MACD': 'A trend-following momentum indicator that shows the relationship between two moving averages of prices. The MACD is calculated by subtracting the 26-day exponential moving average (EMA) from the 12-day EMA',
               'Fast_Exp_Moving_Avg': 'This is a first-order infinite impulse response filter that applies weighting factors which decrease exponentially. Basically, a fancy moving average.',
               'avg_industry_return': 'The Average returns of the industry the stock is a part of.',
               'Moving_Std_Deviation': 'The standard deviation over a period of 20-days'
               }

    links = {'OPENPRC': '', 
            'SHROUT': '', 
            'Moving_Avg': 'https://en.wikipedia.org/wiki/Moving_average', 
            'Ultimate_Oscillator': 'http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ultimate_oscillator',
            'VOL': '',
            'Stochastic_Oscillator': 'https://school.stockcharts.com/doku.php?id=technical_indicators:stochastic_oscillator_fast_slow_and_full',
            'BIDLO': '',
            'ASKHI': '',
            'Slow_Exp_Moving_Avg': 'https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average',
            'return': '',
            'RSI_Indicator': 'https://www.investopedia.com/terms/r/rsi.asp',
            'BollingerB_DOWN': 'https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_bands',
            'BollingerB_UP': 'https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_bands',
            'Momentum_Factor': 'https://school.stockcharts.com/doku.php?id=technical_indicators:rate_of_change_roc_and_momentum',
            'PRC': '',
            'MACD': 'https://www.investopedia.com/terms/m/macd.asp',
            'Fast_Exp_Moving_Avg': 'https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average',
            'avg_industry_return': '',
            'Moving_Std_Deviation': 'https://en.wikipedia.org/wiki/Moving_average'
            }

    classes = ['High', 'High', 'High', 'Medium', 'Medium', 'Medium', 'Medium', 'Medium', 'Low', 'Low', 'Low', 'Low', 'Low', 'Low',  'Almost None', 'Almost None', 'Almost None', 'Almost None', 'Almost None', 'Almost None']

    scores = [[feature, weight]for feature, weight in feature_scores.items()]

    scores.sort(key = lambda x: x[1], reverse = True)

    for i, score in enumerate(scores):
        feature = score[0]
        score[1] = str(score[1])
        score.append(classes[i])
        score.append(descriptors[feature])
        score.append(links[feature])

    results = {
        'prediction' : str(prediction),
        'confidence' : str(confidence),
        'feature_importance': feature_scores,
        'descriptions' : scores 
    }
    end = time.time()

    print(end - start)
    
    return jsonify(results)
示例#5
0
def add_momentum_ta(
    df: pd.DataFrame,
    high: str,
    low: str,
    close: str,
    volume: str,
    fillna: bool = False,
    colprefix: str = "",
    vectorized: bool = False,
) -> pd.DataFrame:
    """Add trend technical analysis features to dataframe.

    Args:
        df (pandas.core.frame.DataFrame): Dataframe base.
        high (str): Name of 'high' column.
        low (str): Name of 'low' column.
        close (str): Name of 'close' column.
        volume (str): Name of 'volume' column.
        fillna(bool): if True, fill nan values.
        colprefix(str): Prefix column names inserted
        vectorized(bool): if True, use only vectorized functions indicators

    Returns:
        pandas.core.frame.DataFrame: Dataframe with new features.
    """

    # Relative Strength Index (RSI)
    df[f"{colprefix}momentum_rsi"] = RSIIndicator(close=df[close],
                                                  window=14,
                                                  fillna=fillna).rsi()

    # Stoch RSI (StochRSI)
    indicator_srsi = StochRSIIndicator(close=df[close],
                                       window=14,
                                       smooth1=3,
                                       smooth2=3,
                                       fillna=fillna)
    df[f"{colprefix}momentum_stoch_rsi"] = indicator_srsi.stochrsi()
    df[f"{colprefix}momentum_stoch_rsi_k"] = indicator_srsi.stochrsi_k()
    df[f"{colprefix}momentum_stoch_rsi_d"] = indicator_srsi.stochrsi_d()

    # TSI Indicator
    df[f"{colprefix}momentum_tsi"] = TSIIndicator(close=df[close],
                                                  window_slow=25,
                                                  window_fast=13,
                                                  fillna=fillna).tsi()

    # Ultimate Oscillator
    df[f"{colprefix}momentum_uo"] = UltimateOscillator(
        high=df[high],
        low=df[low],
        close=df[close],
        window1=7,
        window2=14,
        window3=28,
        weight1=4.0,
        weight2=2.0,
        weight3=1.0,
        fillna=fillna,
    ).ultimate_oscillator()

    # Stoch Indicator
    indicator_so = StochasticOscillator(
        high=df[high],
        low=df[low],
        close=df[close],
        window=14,
        smooth_window=3,
        fillna=fillna,
    )
    df[f"{colprefix}momentum_stoch"] = indicator_so.stoch()
    df[f"{colprefix}momentum_stoch_signal"] = indicator_so.stoch_signal()

    # Williams R Indicator
    df[f"{colprefix}momentum_wr"] = WilliamsRIndicator(
        high=df[high], low=df[low], close=df[close], lbp=14,
        fillna=fillna).williams_r()

    # Awesome Oscillator
    df[f"{colprefix}momentum_ao"] = AwesomeOscillatorIndicator(
        high=df[high], low=df[low], window1=5, window2=34,
        fillna=fillna).awesome_oscillator()

    # Rate Of Change
    df[f"{colprefix}momentum_roc"] = ROCIndicator(close=df[close],
                                                  window=12,
                                                  fillna=fillna).roc()

    # Percentage Price Oscillator
    indicator_ppo = PercentagePriceOscillator(close=df[close],
                                              window_slow=26,
                                              window_fast=12,
                                              window_sign=9,
                                              fillna=fillna)
    df[f"{colprefix}momentum_ppo"] = indicator_ppo.ppo()
    df[f"{colprefix}momentum_ppo_signal"] = indicator_ppo.ppo_signal()
    df[f"{colprefix}momentum_ppo_hist"] = indicator_ppo.ppo_hist()

    # Percentage Volume Oscillator
    indicator_pvo = PercentageVolumeOscillator(volume=df[volume],
                                               window_slow=26,
                                               window_fast=12,
                                               window_sign=9,
                                               fillna=fillna)
    df[f"{colprefix}momentum_pvo"] = indicator_pvo.pvo()
    df[f"{colprefix}momentum_pvo_signal"] = indicator_pvo.pvo_signal()
    df[f"{colprefix}momentum_pvo_hist"] = indicator_pvo.pvo_hist()

    if not vectorized:
        # KAMA
        df[f"{colprefix}momentum_kama"] = KAMAIndicator(close=df[close],
                                                        window=10,
                                                        pow1=2,
                                                        pow2=30,
                                                        fillna=fillna).kama()

    return df
示例#6
0
def add_momentum_ta(df: pd.DataFrame,
                    high: str,
                    low: str,
                    close: str,
                    volume: str,
                    fillna: bool = False,
                    colprefix: str = "") -> pd.DataFrame:
    """Add trend technical analysis features to dataframe.

    Args:
        df (pandas.core.frame.DataFrame): Dataframe base.
        high (str): Name of 'high' column.
        low (str): Name of 'low' column.
        close (str): Name of 'close' column.
        fillna(bool): if True, fill nan values.
        colprefix(str): Prefix column names inserted

    Returns:
        pandas.core.frame.DataFrame: Dataframe with new features.
    """

    # Relative Strength Index (RSI)
    df[f'{colprefix}momentum_rsi'] = RSIIndicator(close=df[close],
                                                  n=14,
                                                  fillna=fillna).rsi()

    # TSI Indicator
    df[f'{colprefix}momentum_tsi'] = TSIIndicator(close=df[close],
                                                  r=25,
                                                  s=13,
                                                  fillna=fillna).tsi()

    # Ultimate Oscillator
    df[f'{colprefix}momentum_uo'] = UltimateOscillator(high=df[high],
                                                       low=df[low],
                                                       close=df[close],
                                                       s=7,
                                                       m=14,
                                                       len=28,
                                                       ws=4.0,
                                                       wm=2.0,
                                                       wl=1.0,
                                                       fillna=fillna).uo()

    # Stoch Indicator
    indicator = StochasticOscillator(high=df[high],
                                     low=df[low],
                                     close=df[close],
                                     n=14,
                                     d_n=3,
                                     fillna=fillna)
    df[f'{colprefix}momentum_stoch'] = indicator.stoch()
    df[f'{colprefix}momentum_stoch_signal'] = indicator.stoch_signal()

    # Williams R Indicator
    df[f'{colprefix}momentum_wr'] = WilliamsRIndicator(high=df[high],
                                                       low=df[low],
                                                       close=df[close],
                                                       lbp=14,
                                                       fillna=fillna).wr()

    # Awesome Oscillator
    df[f'{colprefix}momentum_ao'] = AwesomeOscillatorIndicator(
        high=df[high], low=df[low], s=5, len=34, fillna=fillna).ao()

    # KAMA
    df[f'{colprefix}momentum_kama'] = KAMAIndicator(close=df[close],
                                                    n=10,
                                                    pow1=2,
                                                    pow2=30,
                                                    fillna=fillna).kama()

    # Rate Of Change
    df[f'{colprefix}momentum_roc'] = ROCIndicator(close=df[close],
                                                  n=12,
                                                  fillna=fillna).roc()
    return df
示例#7
0
文件: momentum.py 项目: venkiiee/ta
 def setUp(self):
     self._df = pd.read_csv(self._filename, sep=',')
     self._indicator = UltimateOscillator(
         high=self._df['High'], low=self._df['Low'], close=self._df['Close'],
         s=7, m=14, len=28, ws=4.0, wm=2.0, wl=1.0, fillna=False)