量化百科

Python获取美元人民币实时汇率

由small_q创建,最终由bqewhzw6 被浏览 202 用户

摘要

本文介绍如何如使用Python3获取美元人民币实时汇率。

数据来源

经过查找分析多种数据渠道,我们最终选定使用和讯外汇的行情数据。其网页地址为

http://quote.forex.hexun.com/USDCNY.shtml

通过监测http,得到其api接口为

http://webforex.hermes.hexun.com/forex/quotelist?code=FOREXUSDCNY&column=Code,Name,DateTime,Price,Amount,Volume,LastClose,Open,High,Low,UpDown,UpDownRate,Speed,PriceWeight,AveragePrice,OpenTime,CloseTime,EntrustRatio,EntrustDiff,OutVolume,InVolume,ExchangeRatio,TotalPrice,LastSettle,SettlePrice,BuyPrice,BuyVolume,SellPrice,SellVolume,VolumeRatio,PE,LastVolume,LastCount,LastInOut,VibrationRatio,Total,DealCount,OpenPosition,ClosePosition,PositionDiff,LastPositions,AddPosition,OpenInterest 

经分析并简化,只需要以下字段即可

http://webforex.hermes.hexun.com/forex/quotelist?code=FOREXUSDCNY&column=Code,Price

其返回的数据为

({"Data":[[["USDCNY",65500]]]});

程序实现

很简单,先取数据,再正则提取,最后字典里取值。

代码如下

# -*- coding: utf-8 -*-
# @Author: fangbei
# @Date:   2017-08-26

import re
import json
import urllib.request

url = "http://webforex.hermes.hexun.com/forex/quotelist?code=FOREXUSDCNY&column=Code,Price"
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
html = f.read().decode("utf-8")
print(html)

s = re.findall("{.*}",str(html))[0]
sjson = json.loads(s)

USDCNY = sjson["Data"][0][0][1]/10000
print(USDCNY)

运行效果

{w:100}

标签

Python