@Channelchan
2019-03-27T20:57:14.000000Z
字数 2715
阅读 65969
-----------------------------------By Patrick 黄瀚祺
可导入品种类型:Oanda、A股、商品期货、OKEX、binance
vnpy_fxdayu: https://github.com/xingetouzi/vnpy_fxdayu
Mongodb: https://www.mongodb.com/download-center#community
安装说明: https://github.com/xingetouzi/vnpy_fxdayu/wiki/Windows环境安装
建议安装robomongo作为可视化数据库管理
import pandas as pd
from datetime import datetime,timedelta
import requests
count
为返回的蜡烛数,如果没有指定,数量将默认为500,最大可接受值数是5000。
candleFormat
为可选的蜡烛参数表示,“midpoint” - 基于中点的参数。“bidask” - 基于买/卖的参数,如果未指定candleFormat参数,candleFormat的默认值为“bidask”。
granularity
为可选每个参数表示的时间范围。
秒可选为S5、S10、S15、S30、M1;
分钟可选为M2、M3、M4、M5、M10、M15、M30、H1;
小时可选为H2、H3、H4、H6、H8、H12、D.
其中D为1day,W为1week,M为1month.
url
中自行修改start的时间,其中T15
为15点,表示收集当天15点以后的数据。
获取数据后,再将数据转换为dataframe的格式。
若收集一定区间的数据,在末端加上&end=
import json
# OANDA
def getCandles(instrument,granularity,candleFormat=None,count=None,start=None):
params = {'instrument':instrument,'granularity':granularity,'candleFormat':candleFormat,'count':count,'start':start}
url = "https://api-fxtrade.oanda.com/v1/candles"
r = requests.get(url, headers={"contentType": "application/x-www-form-urlencoded"}, params=params,timeout=10)
text = json.loads(r.content)
data = pd.DataFrame(text["candles"])
data["datetime"] = data["time"].apply(pd.to_datetime)
data.rename(columns={'closeMid':'close', 'highMid':'high', 'lowMid':'low', 'openMid':'open'}, inplace = True)
return data
getCandles('XAU_USD','M1','midpoint',start = '2018-10-29').tail()
# granularity available:S5/ S10/ S15/ S30/ M1/ M2/ M3/ M4/ M5/ M10/ M15/ M30/ H1/ H2/ H3/ H4/ H6/ H8/ H12/ D/ W/ M
close | complete | high | low | open | time | volume | datetime | |
---|---|---|---|---|---|---|---|---|
495 | 1230.4085 | True | 1230.500 | 1230.387 | 1230.4280 | 2018-10-29T08:36:00.000000Z | 9 | 2018-10-29 08:36:00 |
496 | 1230.2030 | True | 1230.459 | 1230.203 | 1230.3680 | 2018-10-29T08:37:00.000000Z | 8 | 2018-10-29 08:37:00 |
497 | 1230.0775 | True | 1230.162 | 1230.078 | 1230.1620 | 2018-10-29T08:38:00.000000Z | 3 | 2018-10-29 08:38:00 |
498 | 1230.0235 | True | 1230.204 | 1229.993 | 1230.0365 | 2018-10-29T08:39:00.000000Z | 18 | 2018-10-29 08:39:00 |
499 | 1229.9695 | True | 1230.113 | 1229.812 | 1229.9830 | 2018-10-29T08:40:00.000000Z | 50 | 2018-10-29 08:40:00 |
symbol = 'XAU_USD'
data =getCandles(symbol,'M1','midpoint',start = '2018-10-29')
import pymongo
client = pymongo.MongoClient('localhost', 27017)
collection = client['FinData'][symbol]
collection.create_index([('datetime', pymongo.ASCENDING)], unique=True)
for index, row in data.iterrows():
bar = {}
bar['open'] = row.open
bar['close'] = row.close
bar['high'] = row.high
bar['low'] = row.low
bar['volume'] = row.volume
bar['symbol'] = symbol
bar['datetime'] = row.datetime
bar['date'] = bar['datetime'].date().strftime('%Y%m%d')
bar['time'] = bar['datetime'].time().strftime('%H:%M:%S')
flt = {'datetime': bar['datetime']}
collection.update_one(flt, {'$set':bar}, upsert=True)