0

I have the following code:

import MetaTrader5 as mt5
import pandas as pd
import time
import pandas_ta as ta
import mplfinance as mpf

pd.set_option('display.max_columns', 500) 
pd.set_option('display.width', 1500)      

if not mt5.initialize():
    print("initialize failed")
    mt5.shutdown()

account="FOO"
authorized=mt5.login(account, server="FOO")
if authorized:
    print("Authorized")
else:
    print("failed to connect at account #{}, error code: {}".format(account, mt5.last_error()))

cndl_72 = mt5.copy_rates_from_pos("BTCUSD", mt5.TIMEFRAME_M1, 1, 72)
cndl_72_df = pd.DataFrame(cndl_72) 
cndl_72_df['time']=pd.to_datetime(cndl_72_df['time'], unit='s') 
cndl_72_df.rename(columns={'time': 'date', 'tick_volume' : 'volume'}, inplace=True)
cndl_72_df.set_index('date', inplace=True)
cndl_72_df.drop(['spread','real_volume'], axis=1, inplace=True)
mpf.plot(cndl_72_df, type='candle')

The objective is to get an MACD indicator to appear.

EDIT #1: see attempt #1 in comments. changes throw a key error.
EDIT #2: see changes https://pastebin.com/qAiu1PkS, which throws a new error:

EDIT #3: type error fixed, now I can successfully calculate MACD from my dataframe and append it if necessary. Now I need to figure out charting...

EDIT #4: charting done, see comments. The MACD plot looks similar so the data could be accurate. Just need to make it prettier...

Authorized
Traceback (most recent call last):
  File "C:\Users\hello\Documents\projects\alerter_venv\main.py", line 38, in <module>
    mpf.plot(cndl_72_df, type='candle', addplot=plots)
  File "C:\Users\hello\Documents\projects\alerter_venv\lib\site-packages\mplfinance\plotting.py", line 707, in plot
    ax = _addplot_columns(panid,panels,ydata,apdict,xdates,config)
  File "C:\Users\hello\Documents\projects\alerter_venv\lib\site-packages\mplfinance\plotting.py", line 997, in _addplot_columns
    yd = [y for y in ydata if not math.isnan(y)]
  File "C:\Users\hello\Documents\projects\alerter_venv\lib\site-packages\mplfinance\plotting.py", line 997, in <listcomp>
    yd = [y for y in ydata if not math.isnan(y)]
TypeError: must be real number, not str

As far as I can tell there aren't any strings that could be producing this. How do I find the source?

Fingers
  • 373
  • 3
  • 18
  • Attempt #1: https://pastebin.com/GHa482qJ throws key error in output: https://pastebin.com/eGzgMbzM – Fingers Feb 21 '22 at 22:37
  • Isn't the cause of the error the code for getting the MACD specified in ta-lib? Also, you are using the histogram value as the color setting condition before you can get the value. – r-beginners Feb 22 '22 at 05:08
  • **Take a close look at your output**. The key error is from pandas trying to access a column that is not there. It says line 31, ***but*** that line number does not match up with your code because the error output also shows the line `colors = [...]` (which is line 27 in your *posted* code). In that line of code (`colors = ...`) you are referencing column `"macd_hist"` ***before*** that column was created (actual line 31 in the *posted* code, where you call `ta.MACD`). – Daniel Goldfarb Feb 22 '22 at 14:01
  • To get rid of the key error, you need to move this line of code `cndl_72_df["macd"], cndl_72_df["macd_signal"], cndl_72_df["macd_hist"] = ta.MACD(cndl_72_df['Close'])` ***up*** to *above all the other lines of code that reference those columns*, since it is this line of code that creates those columns in the first place. – Daniel Goldfarb Feb 22 '22 at 14:23
  • thanks but there are more errors I will continue to work on it and edit if I can't figure it out... – Fingers Feb 22 '22 at 15:35
  • So if I just print the dataframe I have without charting it I get https://pastebin.com/bYtqZzHA. In every row it doesn't give an integer for the macd value but is instead a string that says "MACD_12_29_9". Thats why I'm getting a type error. If I can find a way to correct those macd columns then it should work. – Fingers Feb 22 '22 at 22:50
  • Hey @DanielGoldfarb I did it! code: https://pastebin.com/DSMkwBnM chart: https://imgur.com/a/eNornZB . Is it right? Looks kinda wonky. I would like for there to be more space between the MACD chart and the Candlestick chart. Also the MACD and Signal lines seem drawn in a displaced manner above the histogram. – Fingers Feb 23 '22 at 15:18
  • @Fingers glad you got it working. The plot looks reasonable to me. If you would like me to actually check it though, I would need the actual data. Just ***before*** calling `cndl_72_df.ta.macd()` you could call `cndl_72_df.to_csv('filename.csv')` and then post the csv file somewhere (assuming it is not proprietary data). – Daniel Goldfarb Feb 23 '22 at 18:05
  • @DanielGoldfarb https://www.filemail.com/d/uxfnafityzkdhyc thanks – Fingers Feb 23 '22 at 22:32

1 Answers1

1

working code:

import MetaTrader5 as mt5
import pandas as pd
import pandas_ta as ta
import mplfinance as mpf
 
pd.set_option('display.max_columns', 500) 
pd.set_option('display.width', 1500) 
 
if not mt5.initialize():
    print("initialize failed")
    mt5.shutdown()
 
account="HIDDEN"
authorized=mt5.login(account, server="HIDDEN")
if authorized:
    print("Authorized")
else:
    print("failed to connect at account #{}, error code: {}".format(account, mt5.last_error()))
 
cndl_72 = mt5.copy_rates_from_pos("BTCUSD", mt5.TIMEFRAME_M5, 1, 144)
cndl_72_df = pd.DataFrame(cndl_72) 
cndl_72_df['time']=pd.to_datetime(cndl_72_df['time'], unit='s') 
cndl_72_df.rename(columns={'time': 'date', 'tick_volume' : 'volume'}, inplace=True)
cndl_72_df.set_index('date', inplace=True)
cndl_72_df.drop(['spread','real_volume'], axis=1, inplace=True)
 
macd = cndl_72_df.ta.macd(close='close', fast=12, slow=26, signal=9)
 
macd_plot = mpf.make_addplot(macd["MACD_12_26_9"], panel=1, color='fuchsia', title="MACD")
macd_hist_plot = mpf.make_addplot(macd["MACDh_12_26_9"], type='bar', panel=1) 
macd_signal_plot = mpf.make_addplot(macd["MACDs_12_26_9"], panel=1, color='b')
plots = [macd_plot, macd_signal_plot, macd_hist_plot]
 
mpf.plot(cndl_72_df, type='candle', style='yahoo', addplot=plots)
Fingers
  • 373
  • 3
  • 18