CEDApy/CEDA/Market/market.py

87 lines
2.5 KiB
Python
Raw Normal View History

2021-06-03 14:09:23 +00:00
import re
import io
2021-05-27 12:33:56 +00:00
import requests
import demjson
import pandas as pd
2021-06-03 14:09:23 +00:00
from bs4 import BeautifulSoup
from datetime import datetime
from urllib.parse import quote, urlencode
2021-05-27 12:33:56 +00:00
from fake_useragent import UserAgent
url = {
2021-06-03 14:09:23 +00:00
"dukascopy": "http://data.uicstat.com/api_1.0",
"moneywatch": "https://www.marketwatch.com/investing/"
2021-05-27 12:33:56 +00:00
}
2021-05-29 08:43:15 +00:00
2021-06-03 14:09:23 +00:00
def dukascopy(
2021-05-29 08:43:15 +00:00
instrument: str,
startdate: str,
enddate: str,
timeframe: str,
pricetype: str,
volume: bool,
flat: bool):
2021-05-27 12:33:56 +00:00
tmp_url = url["dukascopy"]
ua = UserAgent()
request_header = {"User-Agent": ua.random}
request_params = {
"instrument": "{}".format(instrument),
"startdate": "{}".format(startdate),
"enddate": "{}".format(enddate),
"timeframe": "{}".format(timeframe),
"pricetype": "{}".format(pricetype),
"volume": "{}".format(volume),
"flat": "{}".format(flat)
}
2021-05-29 08:43:15 +00:00
r = requests.get(tmp_url, params=request_params, headers=request_header)
2021-05-27 12:33:56 +00:00
data_text = r.text
data_json = demjson.decode(data_text)
df = pd.DataFrame(data_json['result'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
df.columns = [
"Date",
"Open",
"High",
"Low",
"Close",
"Volume"
]
return df
2021-06-03 14:09:23 +00:00
def currency_list(instrument = "eurusd", startdate="01/01/2020", enddate = "01/01/2021"):
"""
https://www.marketwatch.com/investing/
"""
tmp_url = url["moneywatch"] + "currency/{}/downloaddatapartial".format(instrument)
ua = UserAgent()
request_header = {"User-Agent": ua.random}
request_params = urlencode({
"startdate": r"{}".format(startdate),
"enddate": r"{}".format(enddate),
"daterange": "d30",
"frequency": "p1d",
"csvdownload": "true",
"downloadpartial": "false",
"newdates": "false"}, quote_via= quote)
r = requests.get(tmp_url, params=request_params, headers=request_header)
data_text = r.content
df = pd.read_csv(io.StringIO(data_text.decode('utf-8')))
Date = []
for i in range(0, len(df)):
Date.append(datetime.strptime(df["Date"][i], "%m/%d/%Y"))
df["Date"] = Date
return df
2021-05-29 08:43:15 +00:00
2021-05-27 12:33:56 +00:00
if __name__ == "__main__":
2021-06-03 14:09:23 +00:00
data = dukascopy(instrument="eurusd",
2021-05-29 08:43:15 +00:00
startdate="2020-01-01",
enddate="2021-01-01",
timeframe="d1",
pricetype="bid",
volume=True,
flat=True)