'Compare Last Index of a Dataframe with a Single Index Dataframe
I'm trying to write a program that will stream candlestick data from MT5:
import MetaTrader5 as mt5
import pandas as pd
from pandas.testing import assert_frame_equal
import time
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1500)
if not mt5.initialize(): # start mt5
print("initialize failed")
mt5.shutdown()
account="HIDDEN" # account info to log into broker
authorized=mt5.login(account, server="HIDDEN")
if authorized:
print("Authorized")
else:
print("failed to connect at account #{}, error code: {}".format(account, mt5.last_error()))
# download last 10 bars of BTCUSD
bars = mt5.copy_rates_from_pos("BTCUSD", mt5.TIMEFRAME_M5, 0, 10)
bars_frame = pd.DataFrame(bars) # convert to DataFrame
bars_frame['time']=pd.to_datetime(bars_frame['time'], unit='s') # some time conversion thing from the documentation I don't really get it
while True: # start the stream
bar_0 = mt5.copy_rates_from_pos("BTCUSD", mt5.TIMEFRAME_M5, 0, 1) # download latest bar
bar_0_frame = pd.DataFrame(bar_0) # convert to DataFrame
bar_0_frame['time']=pd.to_datetime(bar_0_frame['time'], unit='s') # do necessary time conversion
# check if the most recent bar is the same as the most recent entry in bars_frame
if assert_frame_equal(bar_0_frame, bars_frame.iloc[-1]):
print("Already on most recent bar.")
else:
print("Found new bar!")
pd.concat([bar_0_frame, bars_frame]) # if the bar is new, append it to bars_frame
time.sleep(30) # pause the loop. only need to check for a new bar every 30 sec.
When I run this I get the following error:
Traceback (most recent call last):
File "C:\Users\hello\Documents\projects\alerter_venv\main.py", line 41, in <module>
if assert_frame_equal(bar_0_frame, bars_frame.iloc[-1]):
File "C:\Users\hello\Documents\projects\alerter_venv\lib\site-packages\pandas\_testing\asserters.py", line 1264, in assert_frame_equal
_check_isinstance(left, right, DataFrame)
File "C:\Users\hello\Documents\projects\alerter_venv\lib\site-packages\pandas\_testing\asserters.py", line 241, in _check_isinstance
raise AssertionError(
AssertionError: DataFrame Expected type <class 'pandas.core.frame.DataFrame'>, found <class 'pandas.core.series.Series'> instead
I've tried a few different ways of comparing the 2 dataframes and some googling but found nothing useful. Appreciate assistance as always. https://www.mql5.com/en/docs/integration/python_metatrader5
EDIT #3: Please see comments for updated code. I have made several changed to it in an attempt to fix the problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
