Python MetaTrader5 indicators - python

I'm using Metatrader5 module for python and this is my code
'''
#python
from datetime import datetime
import MetaTrader5 as mt5
# display data on the MetaTrader 5 package
print("MetaTrader5 package author: ", mt5.__author__)
print("MetaTrader5 package version: ", mt5.__version__)
# import the 'pandas' module for displaying data obtained in the tabular form
import pandas as pd
pd.set_option('display.max_columns', 500) # number of columns to be displayed
pd.set_option('display.width', 1500) # max table width to display
# import pytz module for working with time zone
import pytz
# establish connection to MetaTrader 5 terminal
if not mt5.initialize():
print("initialize() failed")
mt5.shutdown()
# set time zone to UTC
timezone = pytz.timezone("Etc/UTC")
# create 'datetime' object in UTC time zone to avoid the implementation of a local time zone offset
utc_from = datetime(2020, 1, 10, tzinfo=timezone)
# get 10 EURUSD H4 bars starting from 01.10.2020 in UTC time zone
rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_H4, utc_from, 10)
# shut down connection to the MetaTrader 5 terminal
mt5.shutdown()
# display each element of obtained data in a new line
print("Display obtained data 'as is'")
for rate in rates:
print(rate)
# create DataFrame out of the obtained data
rates_frame = pd.DataFrame(rates)
# convert time in seconds into the datetime format
rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')
# display data
print("\nDisplay dataframe with data")
print(rates_frame)
'''
My question is s there any easy way to calculate stock indicators like RSI and MFI and other indicators using this module?

No. Its possible if using other modules though.
Here is a method using another that could achieve it:
https://www.mql5.com/en/articles/5691
Alternatively, you can pull the data from MT5 and throw it in TA-lib for analysis. TA-lib consumes the data and provides values for the indicators outside MT5.
Check out TA-lib: https://mrjbq7.github.io/ta-lib/

Since your data will be in a pandas df, I would check out pandas-ta, https://pypi.org/project/pandas-ta, all technical indicators. Also, thats a lot of code to pull your data, this is what I use;
import MetaTrader5 as mt
import pandas as pd
from datetime import datetime
mt.initialize()
df = pd.DataFrame( mt.copy_rates_range( '#MNQ', #micro nasd100
mt.TIMEFRAME_D1,
datetime( 2022, 1, 1 ),
datetime.now() ) )
# manipulate as you please
mt.shutdown()
and i didnt like the GMT+2 timezone used by metatrader at first but Ive found its easier to get used to it as the date change is timed to the daily futures market open at 5pm central, which in GMT+2 is day+1 00:00.

Related

How to remove the timezone from yfinance data?

I grab data with yfinance package. I convert it into a panda dataframe.
However, I am unable to save the dataframe to excel file.
ValueError: Excel does not support datetimes with timezones. Please
ensure that datetimes are timezone unaware before writing to Excel.
This is how the dataframe looks like. It should be 8 columns. Spyder says it has 7 columns.
Below is my codes:
import yfinance as yf
import pandas as pd
stock = yf.Ticker("BABA")
# get stock info
stock.info
# get historical market data
hist = stock.history(start="2021-03-25",end="2021-05-20",interval="15m")
hist = pd.DataFrame(hist)
# pd.to_datetime(hist['Datetime'])
# hist['Datetime'].dt.tz_localize(None)
hist.to_excel(excel_writer= "D:/data/python projects/stock_BABA2.xlsx")
You can remove the time zone information of DatetimeIndex using DatetimeIndex.tz_localize() , as follows:
hist.index = hist.index.tz_localize(None)
You can convert time zones using tz_convert(), in your situation it should work with:
hist.index = hist.index.tz_convert(None)

Get last price of stock data in python

I have searched for this topic and I found some packages that are useful. All what I am trying to get is the last price of any specific ticker such as "MSFT"
Here's a code that I found and it is good
import pandas_datareader as pdr
from datetime import datetime
ibm = pdr.get_data_yahoo(symbols='MSFT', start=datetime(2021, 3, 1), end=datetime(2021, 3, 12))
print(ibm['Adj Close'])
This works for range of dates. How can I get the last price only without hard-coding the start date or end date?
Just use tail keyword.
from datetime import datetime, date
ibm = pdr.get_data_yahoo(symbols='MSFT', start = date.today(), end = date.today())
print(ibm['Adj Close'].tail(1))

Converting from Date-Time to GPS time

I want to convert an array of date-time strings (YYYY-MM-DD hh:mm:ss) to GPS seconds (seconds after 2000-01-01 12:00:00) in the python environment.
In order to get the GPS seconds for a single date in Linux BASH, I simply input date2sec datetimestring and it returns a number.
I could do this within a for-loop within python. But, how would I incorporate this within the python script, as it is an external script?
Or, is there another way to convert an array of date-time strings (or single date-time strings incorporated into a for-loop) to GPS time without using date2sec?
Updated Answer: uses Astropy library:
from astropy.time import Time
t = Time('2019-12-03 23:55:32', format='iso', scale='utc')
print(t.gps)
Here you are setting the date in UTC and t.gps converts the datetime to GPS seconds.
Further research showed that directly using datetime objects doesn't take leap seconds into account.
other helpful links here:
How to get current date and time from GPS unsegment time in python
Here is the solution that I used for an entire array of date-times in a for-loop:
import numpy as _np
J2000 = _np.datetime64('2000-01-01 12:00:00') # Time origin
dateTime = [...] # an array of date-times in 'YYYY-MM-DD hh:mm:ss' format
GPSarray_secs = [] # Create new empty array
for i in range(0,len(dateTime)) : # For-loop conversion
GPSseconds = (_np.datetime64(dateTime) - J2000).astype(int) # Calculate GPS seconds
GPSarray_secs = _np.append(GPSarray_secs , GPSseconds) # Append array
The simple conversion for one date-time entry is:
import numpy as _np
J2000 = _np.datetime64('2000-01-01 12:00:00') # Time origin
GPSseconds = (_np.datetime64(dateTime) - J2000).astype(int) # Conversion where dateTime is in 'YYYY-MM-DD hh:mm:ss' format
Importing datetime should not be required.

Darksky Loop through one year of daily data - Datetime Error

I attempt to loop through daily weather data in 2019 using forecastiopy but the error keeps showing. Not sure what the problem is.
import pandas as pd
import requests
import json
from forecastiopy import *
from datetime import date, timedelta, datetime
import datetime
key = 'xxxxx'
city = [40.730610, -73.935242]
start = datetime.datetime(2019, 1, 1)
for day in range(1,365):
fio = ForecastIO.ForecastIO(key,
units=ForecastIO.ForecastIO.UNITS_SI,
lang=ForecastIO.ForecastIO.LANG_ENGLISH,
latitude=city[0],
longitude=city[1],
time=start+datetime.timedelta(day))
daily = FIODaily.FIODaily(fio)
print ('Max Temperature', daily.get_day(day)['temperatureMax'])
print ('Min Temperature:', daily.get_day(day)['temperatureMin'])
print ('Precipitation Pobability:', daily.get_day(day)['precipProbability'])
print ('Precipitation Intensity', daily.get_day(day)['precipIntensity'])
The error shown is below.
ForecastIO.ForecastIO(key,
...,
time=start+datetime.timedelta(day))
Here, the time argument is supposed to be a string that is directly mapped to the Dark Sky API:
time
Either be a UNIX time (that is, seconds since midnight
GMT on 1 Jan 1970) or a string formatted as follows:
[YYYY]-[MM]-[DD]T[HH]:[MM]:[SS][timezone]. [...]
Therefore, you could format the datetime object using isoformat()
ForecastIO.ForecastIO(key,
...,
time=(start+datetime.timedelta(day)).isoformat())

How can I change a month in a DateTime, using for loop (or better method )?

Revised question with appropriate MCVE:
As part of a script I'm writing I need to have a loop that contains a different pair of dates during each iteration, these dates are the first and last available stock trading dates of each month. I have managed to find a calendar with the available dates in an index however despite my research I am not sure how to select the correct dates from this index so that they can be used in the DateTime variables start and end.
Here is as far as my research has got me and I will continue to search for and build my own solution which I will post if I manage to find one:
from __future__ import division
import numpy as np
import pandas as pd
import datetime
import pandas_market_calendars as mcal
from pandas_datareader import data as web
from datetime import date
'''
Full date range:
'''
startrange = datetime.date(2016, 1, 1)
endrange = datetime.date(2016, 12, 31)
'''
Tradable dates in the year:
'''
nyse = mcal.get_calendar('NYSE')
available = nyse.valid_days(start_date='2016-01-01', end_date='2016-12-31')
'''
The loop that needs to take first and last trading date of each month:
'''
dict1 = {}
for i in available:
start = datetime.date('''first available trade day of the month''')
end = datetime.date('''last available trade day of the month''')
diffdays = ((end - start).days)/365
dict1 [i] = diffdays
print (dict1)
That is probably because 1 January 2016 was not a trading day. To check if I am right, try giving it the date 4 January 2016, which was the following Monday. If that works, then you will have to be more sophisticated about the dates you ask for.
Look in the documentaion for dm.BbgDataManager(). It is possible that you can ask it what dates are available.

Categories

Resources