how can i see macd signal by using stockstats?

  • Last Update :
  • Techknowledgy :
  • you can't get it, unless you update the class
    • you need to return fast = df[ema_short]
  • MACD_EMA_SHORT is a parameter used for a calculation in _get_macd
    • MACD_EMA_SHORT = 12
    • ema_short = 'close_{}_ema'.format(cls.MACD_EMA_SHORT)
    • ema_short = 'close_12_ema'
class StockDataFrame(pd.DataFrame):
   OPERATORS = ['le', 'ge', 'lt', 'gt', 'eq', 'ne']

# Start of options.
KDJ_PARAM = (2.0 / 3.0, 1.0 / 3.0)
KDJ_WINDOW = 9

BOLL_PERIOD = 20
BOLL_STD_TIMES = 2

MACD_EMA_SHORT = 12
MACD_EMA_LONG = 26
MACD_EMA_SIGNAL = 9
    @classmethod
    def _get_macd(cls, df):
       ""
    " Moving Average Convergence Divergence
    This
    function will initialize all following columns.
    MACD Line(macd): (12 - day EMA - 26 - day EMA)
    Signal Line(macds): 9 - day EMA of MACD Line
    MACD Histogram(macdh): MACD Line - Signal Line: param df: data: return: None ""
    "
    ema_short = 'close_{}_ema'.format(cls.MACD_EMA_SHORT)
    ema_long = 'close_{}_ema'.format(cls.MACD_EMA_LONG)
    ema_signal = 'macd_{}_ema'.format(cls.MACD_EMA_SIGNAL)
    fast = df[ema_short]
    slow = df[ema_long]
    df['macd'] = fast - slow
    df['macds'] = df[ema_signal]
    df['macdh'] = (df['macd'] - df['macds'])
    log.critical("NOTE: Behavior of MACDH calculation has changed as of "
       "July 2017 - it is now 1/2 of previous calculated values")
    cls._drop_columns(df, [ema_short, ema_long, ema_signal])

Code to get the table:

periods = '3600'
resp = requests.get('https://api.cryptowat.ch/markets/poloniex/ethusdt/ohlc', params = {
   'periods': periods
})
data = resp.json()
df = pd.DataFrame(data['result'][periods], columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'amount'])
df['date'] = pd.to_datetime(df['date'], unit = 's')

stock = sdf.retype(df)
print(stock['macds'])

print(stock)

Suggestion : 2

Jan 6, 2022 , Jan 7, 2022 , Released: Jan 7, 2022 , Uploaded Jan 7, 2022 py2 py3

StockDataFrame works as a wrapper for the pandas.DataFrame. You need to Initialize the StockDataFrame with wrap or retype.

import pandas as pd
from stockstats
import StockDataFrame

df = pd.read_csv('stock.csv')
stock = StockDataFrame.wrap(df)

Example: DataFrame loaded from CSV.

          Date Amount Close High Low Volume
          0 20040817 90923240.0 11.20 12.21 11.03 7877900
          1 20040818 52955668.0 10.29 10.90 10.29 5043200
          2 20040819 32614676.0 10.53 10.65 10.30 3116800
             .....................
             2810 20160815 56416636.0 39.58 39.79 38.38 1436706
          2811 20160816 68030472.0 39.66 40.86 39.00 1703600
          2812 20160817 62536480.0 40.45 40.59 39.12 1567600

After conversion to StockDataFrame

              amount close high low volume
              date
              20040817 90923240.0 11.20 12.21 11.03 7877900
              20040818 52955668.0 10.29 10.90 10.29 5043200
              20040819 32614676.0 10.53 10.65 10.30 3116800
                 ..................
                 20160815 56416636.0 39.58 39.79 38.38 1436706
              20160816 68030472.0 39.66 40.86 39.00 1703600
              20160817 62536480.0 40.45 40.59 39.12 1567600
  • count how many typical price are larger than close in the past 10 periods
In[22]: tp = df['middle']

In[23]: df['res'] = df['middle'] > df['close']

In[24]: df[['middle', 'close', 'res', 'res_-10_c']]
Out[24]:
   middle close res res_10_c
date
20040817 11.480000 11.20 True 1.0
20040818 10.493333 10.29 True 2.0
20040819 10.493333 10.53 False 2.0
20040820 10.486667 10.55 False 2.0
20040823 10.163333 10.10 True 3.0
   ...............
   20160811 38.703333 38.70 True 5.0
20160812 38.916667 39.10 False 5.0
20160815 39.250000 39.58 False 4.0
20160816 39.840000 39.66 True 5.0
20160817 40.053333 40.45 False 5.0

   [2813 rows x 4 columns]
  • Count ups in the past 10 periods
In[26]: df['ups'], df['downs'] = df['change'] > 0, df['change'] < 0

In[27]: df[['ups', 'ups_10_c', 'downs', 'downs_10_c']]
Out[27]:
   ups ups_10_c downs downs_10_c
date
20040817 False 0.0 False 0.0
20040818 False 0.0 True 1.0
20040819 True 1.0 False 1.0
20040820 True 2.0 False 1.0
20040823 False 2.0 True 2.0
   ...............
   20160811 False 3.0 True 7.0
20160812 True 3.0 False 7.0
20160815 True 4.0 False 6.0
20160816 True 5.0 False 5.0
20160817 True 5.0 False 5.0

   [2813 rows x 4 columns]

Suggestion : 3

How can i see MACD signal by using stockstats?,how to find macd and signal for multiple stocks in python using yfinance and pandas?,How can I group by month from a date field using Python and Pandas?,How can I plot a histogram in pandas using nominal values?

  • you can't get it, unless you update the class
    • you need to return fast = df[ema_short]
  • MACD_EMA_SHORT is a parameter used for a calculation in _get_macd
    • MACD_EMA_SHORT = 12
    • ema_short = 'close_{}_ema'.format(cls.MACD_EMA_SHORT)
    • ema_short = 'close_12_ema'
class StockDataFrame(pd.DataFrame):
   OPERATORS = ['le', 'ge', 'lt', 'gt', 'eq', 'ne']

# Start of options.
KDJ_PARAM = (2.0 / 3.0, 1.0 / 3.0)
KDJ_WINDOW = 9

BOLL_PERIOD = 20
BOLL_STD_TIMES = 2

MACD_EMA_SHORT = 12
MACD_EMA_LONG = 26
MACD_EMA_SIGNAL = 9
    @classmethod
    def _get_macd(cls, df):
       ""
    " Moving Average Convergence Divergence
    This
    function will initialize all following columns.
    MACD Line(macd): (12 - day EMA - 26 - day EMA)
    Signal Line(macds): 9 - day EMA of MACD Line
    MACD Histogram(macdh): MACD Line - Signal Line: param df: data: return: None ""
    "
    ema_short = 'close_{}_ema'.format(cls.MACD_EMA_SHORT)
    ema_long = 'close_{}_ema'.format(cls.MACD_EMA_LONG)
    ema_signal = 'macd_{}_ema'.format(cls.MACD_EMA_SIGNAL)
    fast = df[ema_short]
    slow = df[ema_long]
    df['macd'] = fast - slow
    df['macds'] = df[ema_signal]
    df['macdh'] = (df['macd'] - df['macds'])
    log.critical("NOTE: Behavior of MACDH calculation has changed as of "
       "July 2017 - it is now 1/2 of previous calculated values")
    cls._drop_columns(df, [ema_short, ema_long, ema_signal])

Code to get the table:

periods = '3600'
resp = requests.get('https://api.cryptowat.ch/markets/poloniex/ethusdt/ohlc', params = {
   'periods': periods
})
data = resp.json()
df = pd.DataFrame(data['result'][periods], columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'amount'])
df['date'] = pd.to_datetime(df['date'], unit = 's')

stock = sdf.retype(df)
print(stock['macds'])

print(stock)

Suggestion : 4

Dec 17, 2017

from_symbol = 'BTC'
to_symbol = 'USD'
exchange = 'Bitstamp'
datetime_interval = 'day'
import requests
from datetime
import datetime

def get_filename(from_symbol, to_symbol, exchange, datetime_interval, download_date):
   return '%s_%s_%s_%s_%s.csv' % (from_symbol, to_symbol, exchange, datetime_interval, download_date)

def download_data(from_symbol, to_symbol, exchange, datetime_interval):
   supported_intervals = {
      'minute',
      'hour',
      'day'
   }
assert datetime_interval in supported_intervals, \
   'datetime_interval should be one of %s' % supported_intervals

print('Downloading %s trading data for %s %s from %s' %
   (datetime_interval, from_symbol, to_symbol, exchange))
base_url = 'https://min-api.cryptocompare.com/data/histo'
url = '%s%s' % (base_url, datetime_interval)

params = {
   'fsym': from_symbol,
   'tsym': to_symbol,
   'limit': 2000,
   'aggregate': 1,
   'e': exchange
}
request = requests.get(url, params = params)
data = request.json()
return data

def convert_to_dataframe(data):
   df = pd.io.json.json_normalize(data, ['Data'])
df['datetime'] = pd.to_datetime(df.time, unit = 's')
df = df[['datetime', 'low', 'high', 'open',
   'close', 'volumefrom', 'volumeto'
]]
return df

def filter_empty_datapoints(df):
   indices = df[df.sum(axis = 1) == 0].index
print('Filtering %d empty datapoints' % indices.shape[0])
df = df.drop(indices)
return df

data = download_data(from_symbol, to_symbol, exchange, datetime_interval)
df = convert_to_dataframe(data)
df = filter_empty_datapoints(df)

current_datetime = datetime.now().date().isoformat()
filename = get_filename(from_symbol, to_symbol, exchange, datetime_interval, current_datetime)
print('Saving data to %s' % filename)
df.to_csv(filename, index = False)
Downloading day trading data
for BTC USD from Bitstamp
Filtering 877 empty datapoints
Saving data to BTC_USD_Bitstamp_day_2017 - 12 - 25. csv
import pandas as pd

def read_dataset(filename):
   print('Reading data from %s' % filename)
df = pd.read_csv(filename)
df.datetime = pd.to_datetime(df.datetime) # change type from object to datetime
df = df.set_index('datetime')
df = df.sort_index() # sort by datetime
print(df.shape)
return df

df = read_dataset(filename)
Reading data from BTC_USD_Bitstamp_day_2017 - 12 - 25. csv(1124, 6)
from stockstats
import StockDataFrame
df = StockDataFrame.retype(df)
df['macd'] = df.get('macd') # calculate MACD

Suggestion : 5

This tutorial will allow you to grasp a general idea on handling stock prices using Python, understand the candles prices format (OHLC), and plot them using Candlestick charts. You will also learn to use many technical indicators using stockstats library. ,Learned the importance of financial indicators and implemented some of them using the stockstats library.,The MACD is calculated by subtracting the 26-period Exponential Moving Average (EMA) from the 12-period EMA. A nine-day EMA of the MACD is called “Signal Line”, which is then plotted with the MACD. ,From the stockstats library we will import StockDataFrame, which is a class that receives as an attribute a pandas DataFrame sorted by time and includes the columns Open-Close-High-Low in this order:

For this tutorial, you will need to install:

pip install pandas - datareader yfinance mpl - finance stockstats

The below code is responsible for importing stock prices of AAPL:

#
import AAPL stock price
df_aapl = pdr.get_data_yahoo("AAPL", start = "2019-01-01", end = "2019-09-30")

To import SPY (SPDR S&P 500 Trust ETF):

#
import SPY stock price
df_spy = pdr.get_data_yahoo("SPY", start = "2019-01-01", end = "2019-09-30")

In this section, we will use matplotlib and mpl_finance libraries to plot the stock prices of AAPLFirst, we will plot the Open-High-Low-Close prices separately:

df_aapl[["Open", "High", "Low", "Close"]].plot()
plt.show()

But as you may have already noticed, the plot is somehow difficult to read due to being charged, we will instead represent the OHLC in a form of a candlestick:

fig = plt.figure(figsize = (10, 10))
ax = plt.subplot()

plot_data = []
for i in range(150, len(df_aapl)):
   row = [
      i,
      df_aapl.Open.iloc[i],
      df_aapl.High.iloc[i],
      df_aapl.Low.iloc[i],
      df_aapl.Close.iloc[i],
   ]
plot_data.append(row)
candlestick_ohlc(ax, plot_data)
plt.show()