一般来说获取股市行情和指数都是需要付费的,并且这些数据你根本无法导出,比如早年看我妈他们炒股用的大富翁等软件。不过现在可以用诸如腾讯、新浪财经等的网页数据,不过顶多是1s级的,不过免费。所以思路就是使用爬虫扒取。
爬虫也不需要你自己写,这里介绍几种易用的数据lib:
开发环境
:
Ubuntu 16.04
/
Python 3.5
pip install easyquotationpip install easyquotation --upgradeimport easyquotationquotation = easyquotation.use('sina') # 新浪 ['sina'] 腾讯 ['tencent', 'qq']获取所有股票行情
quotation.market_snapshot(prefix=True) # prefix 参数指定返回的行情字典中的股票代码 key 是否带 sz/sh 前缀return
{'sh000159': {'name': '国际实业', # 股票名 'buy': 8.87, # 竞买价 'sell': 8.88, # 竞卖价 'now': 8.88, # 现价 'open': 8.99, # 开盘价 'close': 8.96, # 昨日收盘价 'high': 9.15, # 今日最高价 'low': 8.83, # 今日最低价 'turnover': 22545048, # 交易股数 'volume': 202704887.74, # 交易金额 'ask1': 8.88, # 卖一价 'ask1_volume': 111900, # 卖一量 'ask2': 8.89, 'ask2_volume': 54700, 'bid1': 8.87, # 买一价 'bid1_volume': 21800, # 买一量 'bid2': 8.86, 'bid2_volume': 78400, 'date': '2016-02-19', 'time': '14:30:00', ...}, ......quotation.real('162411') # 支持直接指定前缀,如 'sh000001'quotation.stocks(['000001', '162411'])同时获取指数和行情
quotation.stocks(['sh000001', 'sz000001'], prefix=True)更新股票代码
easyquotation.update_stock_codes()选择 jsl 行情
quotation = easyquotation.use('jsl') # ['jsl']获取分级基金信息
quotation.funda() # 参数可选择利率、折价率、交易量、有无下折、是否永续来过滤 quotation.fundb() # 参数如上对应的分级 A 数据
return
{ 150020: {'abrate': '5:5', 'calc_info': None, 'coupon_descr': '+3.0%', 'coupon_descr_s': '+3.0%', 'fund_descr': '每年第一个工作日定折,无下折,A不参与上折,净值<1元无定折', 'funda_amount': 178823, 'funda_amount_increase': '0', 'funda_amount_increase_rt': '0.00%', 'funda_base_est_dis_rt': '2.27%', 'funda_base_est_dis_rt_t1': '2.27%', 'funda_base_est_dis_rt_t2': '-0.34%', 'funda_base_est_dis_rt_tip': '', 'funda_base_fund_id': '163109', 'funda_coupon': '5.75', 'funda_coupon_next': '4.75', 'funda_current_price': '0.783', 'funda_discount_rt': '24.75%', 'funda_id': '150022', 'funda_increase_rt': '0.00%', 'funda_index_id': '399001', 'funda_index_increase_rt': '0.00%', 'funda_index_name': '深证成指', 'funda_left_year': '永续', 'funda_lower_recalc_rt': '1.82%', 'funda_name': '深成指A', 'funda_nav_dt': '2015-09-14', 'funda_profit_rt': '7.74%', 'funda_profit_rt_next': '6.424%', 'funda_value': '1.0405', 'funda_volume': '0.00', 'fundb_upper_recalc_rt': '244.35%', 'fundb_upper_recalc_rt_info': '深成指A不参与上折', 'last_time': '09:18:22', 'left_recalc_year': '0.30411', 'lower_recalc_profit_rt': '-', 'next_recalc_dt': '<span style="font-style:italic">2016-01-04</span>', 'owned': 0, 'status_cd': 'N'}>'}}分级基金套利接口
quotation.fundarb(jsl_username, jsl_password, avolume=100, bvolume=100, ptype='price')jsl_username: 集思录用户名 jsl_password: 集思路登录密码 avolume: A成交额,单位百万 bvolume: B成交额,单位百万 ptype: 溢价计算方式,price=现价,buy=买一,sell=卖一return
"165511":{ 'base_fund_id': '165511', # 母基金代码 'AB_price': '现价A/B : 1.008/1.329', 'a_profit_rt_next': '4.705', 'a_ratio': 4, 'abrate': '4:6', 'apply_fee': '0', 'apply_fee_tip': '0', 'apply_sell': '-0.59', 'asset_ratio': '95%', 'asset_ratio_last': '99%', 'asset_ratio_num': '95.00', 'b_est_val': '1.340', 'b_gangan': '1.502', 'b_ratio': 6, 'base_est_dis_rt': '-0.56%', 'base_est_val': '1.2073', 'base_fund_nm': '信诚500', 'base_lower_recalc_rt': '54.15%', 'base_nav': '1.1970', 'base_nav_dt': '2016-04-13', 'buy1A': '1.007', 'buy1B': '1.329', 'buy1_amountA': '0.201', 'buy1_amountB': '7.123', 'buy_redeem': '-0.51', 'calc_info': None, 'coupon': '0.00%', 'coupon_next': '4.700', 'est_dis_rt': '-0.55%', 'est_time': '2016-04-14 15:10:05', 'fundA_amount': '6667', 'fundA_amount_increase': '-51', 'fundA_amount_increase_rt': '-0.76%', 'fundA_amount_tip': '2016-04-14 A类总份额6667.000万份,份额增长-0.76%', 'fundA_id': '150028', 'fundA_last_dt': '2016-04-14', 'fundA_last_time': '14:57:02', 'fundA_nav': '1.0090', 'fundA_nav_dt': '2016-04-13', 'fundA_nm': '中证500A', 'fundA_stock_volume': '28.2446', 'fundA_stock_volume_tip': 'A类总份额6667.000万份, 成交28万份', 'fundA_turnover_rt': '0.42%', 'fundA_volume': '28.46', 'fundB_amount': 10000.5, 'fundB_amount_increase': '-76', 'fundB_amount_tip': '2016-04-14 B类总份额10000万份,份额增长-0.76%', 'fundB_id': '150029', 'fundB_last_dt': '2016-04-14', 'fundB_last_time': '15:00:27', 'fundB_nav': '1.3220', 'fundB_nav_dt': '2016-04-13', 'fundB_nm': '中证500B', 'fundB_stock_volume': '255.5280', 'fundB_stock_volume_tip': 'B类总份额10000万份, 成交256万份', 'fundB_turnover_rt': '2.56%', 'fundB_volume': '337.24', 'fund_company_nm': '信诚基金', 'funda_name_tip': '下期利率:4.70,修正收益率:4.71%', 'idx_incr_rt': '0.91%', 'increase_rtA': '-0.10%', 'increase_rtB': '1.06%', 'index_id': '399905', 'index_nm': '中证 500', 'is_est_val': 1, 'is_last_nav': 1, 'lower_recalc_rt': '54.15', 'maturity_dt': '-', 'merge_price': '1.2006', 'min_apply_amount': None, 'notes': 'http://www.xcfunds.com/funds_2012/165511/fundinfor.shtml\r\n', 'ownedA': 0, 'ownedM': 1, 'priceA': '1.008', 'priceB': '1.329', 'real_idx_increase_rt': '0.91', 'recalc_to': None, 'redeem_fee': '0.5%', 'redeem_fee_tip': '0.5%', 'sell1A': '1.008', 'sell1B': '1.330', 'sell1_amountA': '7.132', 'sell1_amountB': '16.820', 'status_cd': 'N'指数ETF查询接口
TIP : 尚未包含黄金ETF和货币ETF
quotation.etfindex(index_id="", min_volume=0, max_discount=None, min_discount=None)return
"510050": { "fund_id": "510050", # 代码 "fund_nm": "50ETF", # 名称 "price": "2.066", # 现价 "increase_rt": "0.34%", # 涨幅 "volume": "71290.96", # 成交额(万元) "index_nm": "上证50", # 指数 "pe": "9.038", # 指数PE "pb": "1.151", # 指数PB "index_increase_rt": "0.45%", # 指数涨幅 "estimate_value": "2.0733", # 估值 "fund_nav": "2.0730", # 净值 "nav_dt": "2016-03-11", # 净值日期 "discount_rt": "-0.34%", # 溢价率 "creation_unit": "90", # 最小申赎单位(万份) "amount": "1315800", # 份额 "unit_total": "271.84", # 规模(亿元) "index_id": "000016", # 指数代码 "last_time": "15:00:00", # 价格最后时间(未确定) "last_est_time": "23:50:02", # 估值最后时间(未确定) quotation = easyquotation.use("timekline") data = quotation.real(['603828'], prefix=True)return
'sh603828': { 'date': '170721', #日期 'time_data': { '201707210930': ['0930', '19.42', '61'], # [时间, 当前价, 上一分钟到这一分钟之间的成交数量] '201707210931': ['0931', '19.42','122'], '201707210932': ['0932', '19.43', '123'], '201707210933': ['0933', '19.48', '125'], '201707210934': ['0934', '19.49', '133'], '201707210935': ['0935', '19.48', '161'],港股日k线图
import easyquotation quotation = easyquotation.use("daykline") data = quotation.real(['00001','00700']) print(data)return
'00001': [ ['2017-10-09', '352.00', '349.00', '353.00', '348.60', '13455864.00'], # [日期, 今开, 今收, 最高, 最低, 成交量 ] ['2017-10-10', '350.80', '351.20', '352.60', '349.80', '10088970.00'], '00700':[腾讯港股时时行情
import easyquotation quotation = easyquotation.use("hkquote") data = quotation.real(['00001','00700']) print(data) '00001': 'stock_code': '00001', # 股票代码 'lotSize': '"100', # 每手数量 'name': '长和', # 股票名称 'price': '97.20', # 股票当前价格 'lastPrice': '97.75', # 股票昨天收盘价格 'openPrice': '97.75', # 股票今天开盘价格 'amount': '1641463.0', # 股票成交量 'time': '2017/11/29 15:38:58', # 当前时间 'high': '98.05', # 当天最高价格 'low': '97.15' # 当天最低价格 '00700': 'stock_code': '00700', 'lotSize': '"100', 'name': '腾讯控股', 'price': '413.20', 'lastPrice': '419.20', 'openPrice': '422.20', 'amount': '21351010.0', 'time': '2017/11/29 15:39:01', 'high': '422.80', 'low': '412.40'初始化环境
进入项目目录后运行
make initTushare
TuShare是实现对股票/期货等金融数据从数据采集、清洗加工 到 数据存储过程的工具,满足金融量化分析师和学习数据分析的人在数据获取方面的需求,它的特点是数据覆盖范围广,接口调用简单,响应快速。
Dependencies
Installation
Upgrade
pip install tushare --upgradeQuick Start
Example 1. 获取个股历史交易数据(包括均线数据):
import tushare as ts ts.get_hist_data('600848') #一次性获取全部数据结果显示:
日期 ,开盘价, 最高价, 收盘价, 最低价, 成交量, 价格变动 ,涨跌幅,5日均价,10日均价,20日均价,5日均量,10日均量,20日均量,换手率
open high close low volume p_change ma5 \ 2012-01-11 6.880 7.380 7.060 6.880 14129.96 2.62 7.060 2012-01-12 7.050 7.100 6.980 6.900 7895.19 -1.13 7.020 2012-01-13 6.950 7.000 6.700 6.690 6611.87 -4.01 6.913 2012-01-16 6.680 6.750 6.510 6.480 2941.63 -2.84 6.813 2012-01-17 6.660 6.880 6.860 6.460 8642.57 5.38 6.822 2012-01-18 7.000 7.300 6.890 6.880 13075.40 0.44 6.788 2012-01-19 6.690 6.950 6.890 6.680 6117.32 0.00 6.770 2012-01-20 6.870 7.080 7.010 6.870 6813.09 1.74 6.832 ma10 ma20 v_ma5 v_ma10 v_ma20 turnover 2012-01-11 7.060 7.060 14129.96 14129.96 14129.96 0.48 2012-01-12 7.020 7.020 11012.58 11012.58 11012.58 0.27 2012-01-13 6.913 6.913 9545.67 9545.67 9545.67 0.23 2012-01-16 6.813 6.813 7894.66 7894.66 7894.66 0.10 2012-01-17 6.822 6.822 8044.24 8044.24 8044.24 0.30 2012-01-18 6.833 6.833 7833.33 8882.77 8882.77 0.45 2012-01-19 6.841 6.841 7477.76 8487.71 8487.71 0.21 2012-01-20 6.863 6.863 7518.00 8278.38 8278.38 0.23设定历史数据的时间:
ts.get_hist_data('600848',start='2015-01-05',end='2015-01-09') open high close low volume p_change ma5 ma10 \ 2015-01-05 11.160 11.390 11.260 10.890 46383.57 1.26 11.156 11.212 2015-01-06 11.130 11.660 11.610 11.030 59199.93 3.11 11.182 11.155 2015-01-07 11.580 11.990 11.920 11.480 86681.38 2.67 11.366 11.251 2015-01-08 11.700 11.920 11.670 11.640 56845.71 -2.10 11.516 11.349 2015-01-09 11.680 11.710 11.230 11.190 44851.56 -3.77 11.538 11.363 ma20 v_ma5 v_ma10 v_ma20 turnover 2015-01-05 11.198 58648.75 68429.87 97141.81 1.59 2015-01-06 11.382 54854.38 63401.05 98686.98 2.03 2015-01-07 11.543 55049.74 61628.07 103010.58 2.97 2015-01-08 11.647 57268.99 61376.00 105823.50 1.95 2015-01-09 11.682 58792.43 60665.93 107924.27 1.54复权历史数据
获取历史复权数据,分为前复权和后复权数据,接口提供股票上市以来所有历史数据,默认为前复权。如果不设定开始和结束日期,则返回近一年的复权数据,从性能上考虑,推荐设定开始日期和结束日期,而且最好不要超过一年以上,获取到数据后,请及时在本地存储。ts.get_h_data('002337') #前复权 ts.get_h_data('002337',autype='hfq') #后复权 ts.get_h_data('002337',autype=None) #不复权 ts.get_h_data('002337',start='2015-01-01',end='2015-03-16') #两个日期之间的前复权数据Example 2. 一次性获取最近一个日交易日所有股票的交易数据(结果显示速度取决于网速)
ts.get_today_all()结果显示:
代码,名称,涨跌幅,现价,开盘价,最高价,最低价,最日收盘价,成交量,换手率
code name changepercent trade open high low settlement \ 0 002738 中矿资源 10.023 19.32 19.32 19.32 19.32 17.56 1 300410 正业科技 10.022 25.03 25.03 25.03 25.03 22.75 2 002736 国信证券 10.013 16.37 16.37 16.37 16.37 14.88 3 300412 迦南科技 10.010 31.54 31.54 31.54 31.54 28.67 4 300411 金盾股份 10.007 29.68 29.68 29.68 29.68 26.98 5 603636 南威软件 10.006 38.15 38.15 38.15 38.15 34.68 6 002664 信质电机 10.004 30.68 29.00 30.68 28.30 27.89 7 300367 东方网力 10.004 86.76 78.00 86.76 77.87 78.87 8 601299 中国北车 10.000 11.44 11.44 11.44 11.29 10.40 9 601880 大连港 10.000 5.72 5.34 5.72 5.22 5.20 10 000856 冀东装备 10.000 8.91 8.18 8.91 8.18 8.10 volume turnoverratio 0 375100 1.25033 1 85800 0.57200 2 1058925 0.08824 3 69400 0.51791 4 252220 1.26110 5 1374630 5.49852 6 6448748 9.32700 7 2025030 6.88669 8 433453523 4.28056 9 323469835 9.61735 10 25768152 19.51090Example 3. 获取历史分笔数据
import tushare as ts df = ts.get_tick_data('600848',date='2014-01-09') df.head(10)结果显示:
成交时间、成交价格、价格变动,成交手、成交金额(元),买卖类型
Out[3]: time price change volume amount type 0 15:00:00 6.05 -- 8 4840 卖盘 1 14:59:55 6.05 -- 50 30250 卖盘 2 14:59:35 6.05 -- 20 12100 卖盘 3 14:59:30 6.05 -0.01 165 99825 卖盘 4 14:59:20 6.06 0.01 4 2424 买盘 5 14:59:05 6.05 -0.01 2 1210 卖盘 6 14:58:55 6.06 -- 4 2424 买盘 7 14:58:45 6.06 -- 2 1212 买盘 8 14:58:35 6.06 0.01 2 1212 买盘 9 14:58:25 6.05 -0.01 20 12100 卖盘 10 14:58:05 6.06 -- 5 3030 买盘Example 4. 获取实时交易数据(Realtime Quotes Data)
df = ts.get_realtime_quotes('000581') #Single stock symbol df[['code','name','price','bid','ask','volume','amount','time']]结果显示:
名称、开盘价、昨价、现价、最高、最低、买入价、卖出价、成交量、成交金额…more in docs
code name price bid ask volume amount time 0 000581 威孚高科 31.15 31.14 31.15 8183020 253494991.16 11:30:36请求多个股票方法(一次最好不要超过30个):
ts.get_realtime_quotes(['600848','000980','000981']) #symbols from a list ts.get_realtime_quotes(df['code'].tail(10)) #from a Seriespyalgotrade-cn
策略可视化
在pyalgotrade中,已经为我们提供了很好用的可视化模块了,plotter。所以,一开始我们先导入模块。
from pyalgotrade import plotter把策略的净值图、买卖开仓情况绘制出来其实很简单,把我们的策略实例化之后,传给plotter就可以了。
myStrategy = MyStrategy(feed, "fd")# 策略实例化 plt = plotter.StrategyPlotter(myStrategy) # 传入策略 myStrategy.run()# 运行策略 myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult()) plt.plot()# 绘制 【数据】【自动化交易】Python获取中国股市行情和指数一般来说获取股市行情和指数都是需要付费的,并且这些数据你根本无法导出,比如早年看我妈他们炒股用的大富翁等软件。不过现在可以用诸如腾讯、新浪财经等的网页数据,不过顶多是1s级的,不过免费。所以思路就是使用爬虫扒取。爬虫也不需要你自己写,这里介绍几种易用的数据lib:Tushare: 内核并非爬虫,好像是C++写的,文档比较老了。印象...某API,GET方法,token,mobile,email三个参数token为必填项mobile,email必填其中1项mobile为手机号,email为email格式针对上面的API,在做接口测试时,需要的测试用例动辄会多达10+,这个时候采用数据驱动的方式将共性的内容写入配置文件或许会更合适。这里考虑把API、参数、以及预期结果预行在格式化的CSV里保存,利用csv组件从CSV里读取URL、参数以及预期结果,Requests组件发起请求,将响应结果与预期结果进行比对,最后把比对结果写到结果CSV。流程如下图csv读写CSV文件jsonrequests发起请求,获取响应结果unittest测在接口测试的过程中,很多时候会用到对CSV的读取操作,本文主要说明Python3对CSV的写入和读取。1.需求 在接口测试的过程中,很多时候会用到对CSV的读取操作,本文主要说明Python3对CSV的写入和读取。 1.需求 某API,GET方法,token,mobile,email三个参数 token为必填项 mobile,email必填其中1项 mobile为手机号,email为email格式 2.方案 针对上面的API,在做接口测试时,需要的测试用例动辄会多达10+,这个时候采用数据驱动的方式将共性的内容写入配置文件或许会更合适。 这里考虑把API、参通过Python进行自动基础分析 这个python程序会根据相对于行业的估值,盈利能力,增长和价格绩效指标对100种股票进行评级。 查看文件S&P500StockRatings.csv和MidCap+2BStockRatings作为输出示例 此程序中使用的评分系统基于特定扇区的特定指标的值的正态分布。 例如,如果要对技术部门股票的净利润进行评级,请查看技术部门所有股票的净利润率,并根据价值分布的百分比对股票的净利润率进行评级。 在下图中,我们看到技术行业股票的平均净利润率为1.8%,而第90个百分位数为16.45%。 程序中使用的评分系统在除去异常值后采用一组值的标准偏差,然后将该数字除以3,该值由图中所示的“更改”值表示,等于4.68。 这是用于对每种股票的每个指标进行分级的值。 下图准确显示了每个指标的分级方式,其中图中的每个条形代表“更改”值的1增量。 根据此数字和“1、source bin/activate 即可使当前终端环境变成python3.5的环境,看到终端前辍带有py3venv表明已经成功: (pythonDev) bond@ubuntu:~/pythonDev$ 2、pip install easyquotat未定权益的估值 蒙特卡洛模拟的最重要应用之一是未定权益(期权,衍生品,混合型工具等)的估值。简单地说,在风险中立的世界中,未定权益的价值是风险中立(鞅)测度下的折现后预期收益。这是所有风险因素(股票、指数等)偏离无风险短期利率的概率测度。根据资产定价基本定理,这种概率测度的存在等价于套利机会的缺失。 金融期权表示在规定(行权期)日期(欧式期权)或者规定时期(美式期权)内,以规定价格(所谓行权价 )...使用python代码获取多台服务器信息,要求使用html形式发送表格,适用验证版本(ubuntu16、ubuntu18) ubuntu14版本top输出信息有些差异,此代码不适用。 PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取 python免费学习资料以及群交流解答点击即可加入 import smtplib from email.header import Header from email.mime.text import MIMEText import parami本系列通过一些实例介绍量化的入门知识,适合零基础的初学者。本篇计算三个宽基指数:沪深300、中证500、中证1000的估值百分位,并将其与价格百分位比较。本文的程序运行前要先导入数据源和pandas库:import akshare as ak # 导入数据源 import pandas as pd # 导入pandas库pandas的数据分析功能非常强大,在量化分析中会经常用到,要熟悉掌握。从上一篇《量化入门系列:四行代码实现A股的估值温度计》可以总结出,此类量化分析通常分为三个步骤:第一步打开要获取股市行情,可以通过以下方式使用Python: 1. 使用第三方库:可以使用许多第三方库来获取股市行情,例如Pandas、Numpy、Quandl等。这些库提供了许多函数和方法来获取和处理股市数据。 2. 使用API:许多股市数据提供商提供API,可以使用Python编写代码来调用这些API获取数据。例如,Alpha Vantage、Yahoo Finance等都提供API。 3. 使用Web爬虫:可以使用Python编写Web爬虫来从股市网站上抓取数据。但是,需要注意不要违反网站的使用条款。 以下是使用Python获取股市行情的示例代码: 使用Pandas库获取股票历史数据: ```python import pandas_datareader as pdr import datetime start = datetime.datetime(2021, 1, 1) end = datetime.datetime(2021, 6, 30) df = pdr.get_data_yahoo('AAPL', start=start, end=end) print(df) 使用Alpha Vantage API获取股票历史数据: ```python import requests import json url = 'https://www.alphavantage.co/query' params = { 'function': 'TIME_SERIES_DAILY_ADJUSTED', 'symbol': 'AAPL', 'apikey': 'your_api_key' response = requests.get(url, params=params) data = json.loads(response.text) print(data['Time Series (Daily)']) 使用Web爬虫获取股票历史数据: ```python import requests from bs4 import BeautifulSoup url = 'https://finance.yahoo.com/quote/AAPL/history?p=AAPL' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') table = soup.find('table', attrs={'data-test': 'historical-prices'}) rows = table.find_all('tr') for row in rows[1:]: cols = row.find_all('td') date = cols[0].text open_price = cols[1].text high_price = cols[2].text low_price = cols[3].text close_price = cols[4].text adj_close_price = cols[5].text volume = cols[6].text print(date, open_price, high_price, low_price, close_price, adj_close_price, volume)