Python量化交易学习笔记(十四)demo52——程序化交易,交易时间段内自动买入跟踪股票
本文记录使用easytrader+easyquotation实现策略的程序化交易的流程。上一篇 已经记录了使用easytrader进行程序化交易的过程,本文主要对easyquotation获取实时数据实现策略进行介绍。
- easyquotation安装
pip install easyquotation
- 选择行情数据源
# 选择数据源
import easyquotation as eq
q = eq.use('qq')
-
判断是否进入交易时间9.30-11.30---1:00--3:00
# 判断是否进入交易时间9.30-11.30---1:00--3:00
time_now = datetime.datetime.now()
if time_now.time() < datetime.time(9, 30, 0) \
or datetime.time(11, 30, 0) <= time_now.time() <= datetime.time(13, 0, 0):
continue
if time_now.time() >= datetime.time(15, 0, 0):
print("当前时间:"+time_now.time().strftime('%Y-%m-%d-%H-%M-%S')+"不在交易时间段,退出交易程序化")
break
-
根据时间更新成交量权重
volume_weight = 1
if time_now.time() > datetime.time(13, 0, 0):
delta_seconds = (time_now - datetime.datetime(time_now.year, time_now.month, time_now.day, 13, 0, 0)).total_seconds()
volume_weight = 1 + delta_seconds / 7200
print('\n', time_now)
time_str = time_now.strftime('%Y-%m-%d-%H-%M-%S')
#定义一个买入股票对象
buy_stocks = {}
data = q.stocks(stocks)
print('返回数据:'+data)
-
循环遍历
for key in data:
# 价格过20日均线
ma_20 = (history_data[key]['ma_19'] * 19 + data[key]['now']) / 20
if not data[key]['now'] >= ma_20:
continue
# 涨幅不能过大
if not (data[key]['now'] - data[key]['close']) / data[key]['close'] < 0.0618:
continue
# 成交量
if not data[key]['volume'] > history_data[key]['volume'] * volume_weight:
continue
buy_price = 0.02 + data[key]['now']
if g_trade:
buy_limit = min(balance, 3000)
if 100 * buy_price < balance:
ret = user.buy(key, buy_price, buy_limit // (buy_price * 100) * 100)
print(ret)
buy_stocks[key] = buy_price
stocks.remove(key)
print(key)
C:\Python38\python.exe F:/GZH/stock/src/com/gzh/stock51_buy.py 获取当前目录:F:\GZH\stock\src\com\gzh/../ 股票代码: ['sh600256', 'sh600348', 'sh600968', 'sh600971', 'sh601857', 'sh603300'] 数据:
{
"name": "广汇能源",
"code": "600256",
"now": 3.28,
"close": 3.4,
"open": 3.38,
"volume": 55377600,
"bid_volume": 15774500,
"ask_volume": 39603000,
"bid1": 3.27,
"bid1_volume": 1127100,
"bid2": 3.26,
"bid2_volume": 1612700,
"bid3": 3.25,
"bid3_volume": 1507900,
"bid4": 3.24,
"bid4_volume": 252600,
"bid5": 3.23,
"bid5_volume": 324400,
"ask1": 3.28,
"ask1_volume": 80100,
"ask2": 3.29,
"ask2_volume": 261900,
"ask3": 3.3,
"ask3_volume": 214900,
"ask4": 3.31,
"ask4_volume": 325600,
"ask5": 3.32,
"ask5_volume": 741600,
"最近逐笔成交": "",
"涨跌": -0.12,
"涨跌(%)": -3.53,
"high": 3.39,
"low": 3.27,
"datetime": datetime.datetime(2021, 7, 8, 10, 30, 15),
"价格/成交量(手)/成交额": "3.28/553776/183582685",
"成交量(手)": 55377600,
"成交额(万)": 183580000,
"turnover": 0.82,
"PE": 11.78,
"unknown": "",
"high_2": 3.39,
"low_2": 3.27,
"振幅": 3.53,
"流通市值": 221.53,
"总市值": 221.53,
"PB": 1.25,
"涨停价": 3.74,
"跌停价": 3.06,
"量比": 2.92,
"委差": 32006,
"均价": 3.32,
"市盈(动)": 6.9,
"市盈(静)": 16.58
}