Merge pull request #9 from vertti/replace-with-talib

Use TA-lib for MACD and StochRSI
This commit is contained in:
Michael Egger 2017-09-03 14:49:01 +02:00 committed by GitHub
commit 8ac4fe7734
3 changed files with 28 additions and 23 deletions

View File

@ -40,6 +40,7 @@ if not feel free to raise a github issue.
##### Prerequisites ##### Prerequisites
* python3.6 * python3.6
* sqlite * sqlite
* [TA-lib](https://github.com/mrjbq7/ta-lib#dependencies) binaries
##### Install ##### Install
``` ```

View File

@ -4,18 +4,20 @@ import logging
import arrow import arrow
import requests import requests
from pandas.io.json import json_normalize from pandas.io.json import json_normalize
from stockstats import StockDataFrame from pandas import DataFrame
# from stockstats import StockDataFrame
import talib.abstract as ta
logging.basicConfig(level=logging.DEBUG, logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def get_ticker_dataframe(pair: str) -> StockDataFrame: def get_ticker_dataframe(pair: str) -> DataFrame:
""" """
Analyses the trend for the given pair Analyses the trend for the given pair
:param pair: pair as str in format BTC_ETH or BTC-ETH :param pair: pair as str in format BTC_ETH or BTC-ETH
:return: StockDataFrame :return: DataFrame
""" """
minimum_date = arrow.now() - timedelta(hours=6) minimum_date = arrow.now() - timedelta(hours=6)
url = 'https://bittrex.com/Api/v2.0/pub/market/GetTicks' url = 'https://bittrex.com/Api/v2.0/pub/market/GetTicks'
@ -39,33 +41,35 @@ def get_ticker_dataframe(pair: str) -> StockDataFrame:
'low': t['L'], 'low': t['L'],
'date': t['T'], 'date': t['T'],
} for t in sorted(data['result'], key=lambda k: k['T']) if arrow.get(t['T']) > minimum_date] } for t in sorted(data['result'], key=lambda k: k['T']) if arrow.get(t['T']) > minimum_date]
dataframe = StockDataFrame(json_normalize(data)) dataframe = DataFrame(json_normalize(data))
# calculate StochRSI # calculate StochRSI
window = 14 stochrsi = ta.STOCHRSI(dataframe)
rsi = dataframe['rsi_{}'.format(window)] dataframe['stochrsi'] = stochrsi['fastd'] # values between 0-100, not 0-1
rolling = rsi.rolling(window=window, center=False)
low = rolling.min() macd = ta.MACD(dataframe)
high = rolling.max() dataframe['macd'] = macd['macd']
dataframe['stochrsi'] = (rsi - low) / (high - low) dataframe['macds'] = macd['macdsignal']
dataframe['macdh'] = macd['macdhist']
return dataframe return dataframe
def populate_trends(dataframe: StockDataFrame) -> StockDataFrame: def populate_trends(dataframe: DataFrame) -> DataFrame:
""" """
Populates the trends for the given dataframe Populates the trends for the given dataframe
:param dataframe: StockDataFrame :param dataframe: DataFrame
:return: StockDataFrame with populated trends :return: DataFrame with populated trends
""" """
""" """
dataframe.loc[ dataframe.loc[
(dataframe['stochrsi'] < 0.20) (dataframe['stochrsi'] < 20)
& (dataframe['close_30_ema'] > (1 + 0.0025) * dataframe['close_60_ema']), & (dataframe['close_30_ema'] > (1 + 0.0025) * dataframe['close_60_ema']),
'underpriced' 'underpriced'
] = 1 ] = 1
""" """
dataframe.loc[ dataframe.loc[
(dataframe['stochrsi'] < 0.20) (dataframe['stochrsi'] < 20)
& (dataframe['macd'] > dataframe['macds']), & (dataframe['macd'] > dataframe['macds']),
'underpriced' 'underpriced'
] = 1 ] = 1
@ -93,10 +97,10 @@ def get_buy_signal(pair: str) -> bool:
return signal return signal
def plot_dataframe(dataframe: StockDataFrame, pair: str) -> None: def plot_dataframe(dataframe: DataFrame, pair: str) -> None:
""" """
Plots the given dataframe Plots the given dataframe
:param dataframe: StockDataFrame :param dataframe: DataFrame
:param pair: pair as str :param pair: pair as str
:return: None :return: None
""" """
@ -110,8 +114,8 @@ def plot_dataframe(dataframe: StockDataFrame, pair: str) -> None:
fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True) fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True)
fig.suptitle(pair, fontsize=14, fontweight='bold') fig.suptitle(pair, fontsize=14, fontweight='bold')
ax1.plot(dataframe.index.values, dataframe['close'], label='close') ax1.plot(dataframe.index.values, dataframe['close'], label='close')
ax1.plot(dataframe.index.values, dataframe['close_30_ema'], label='EMA(60)') # ax1.plot(dataframe.index.values, dataframe['close_30_ema'], label='EMA(60)')
ax1.plot(dataframe.index.values, dataframe['close_90_ema'], label='EMA(120)') # ax1.plot(dataframe.index.values, dataframe['close_90_ema'], label='EMA(120)')
# ax1.plot(dataframe.index.values, dataframe['sell'], 'ro', label='sell') # ax1.plot(dataframe.index.values, dataframe['sell'], 'ro', label='sell')
ax1.plot(dataframe.index.values, dataframe['buy'], 'bo', label='buy') ax1.plot(dataframe.index.values, dataframe['buy'], 'bo', label='buy')
ax1.legend() ax1.legend()
@ -123,8 +127,8 @@ def plot_dataframe(dataframe: StockDataFrame, pair: str) -> None:
ax2.legend() ax2.legend()
ax3.plot(dataframe.index.values, dataframe['stochrsi'], label='StochRSI') ax3.plot(dataframe.index.values, dataframe['stochrsi'], label='StochRSI')
ax3.plot(dataframe.index.values, [0.80] * len(dataframe.index.values)) ax3.plot(dataframe.index.values, [80] * len(dataframe.index.values))
ax3.plot(dataframe.index.values, [0.20] * len(dataframe.index.values)) ax3.plot(dataframe.index.values, [20] * len(dataframe.index.values))
ax3.legend() ax3.legend()
# Fine-tune figure; make subplots close to each other and hide x ticks for # Fine-tune figure; make subplots close to each other and hide x ticks for

View File

@ -11,5 +11,5 @@ matplotlib==2.0.2
PYQT5==5.9 PYQT5==5.9
scikit-learn==0.19.0 scikit-learn==0.19.0
scipy==0.19.1 scipy==0.19.1
stockstats==0.2.0
jsonschema==2.6.0 jsonschema==2.6.0
TA-Lib==0.4.10