- #encoding:gbk
- import numpy as np
- import pandas as pd
- import types
- import logging
- logger = logging.getLogger(__name__)
- logging.basicConfig(level=logging.DEBUG)
- trade = types.SimpleNamespace(
- account_id=None,
- stock_code=None,
- )
- def init(ContextInfo):
- trade.account_id = 'test'
- trade.stock_code = f'{ContextInfo.stockcode}.{ContextInfo.market}'
- ContextInfo.start = "2024-04-01 09:30:00"
- ContextInfo.end = "2024-04-10 15:00:00"
- ContextInfo.capital = 1e5
- def handlebar(ContextInfo):
- index = ContextInfo.barpos
- timetag = ContextInfo.get_bar_timetag(index)
- logging.info(f'bar: {timetag_to_datetime(timetag, "%Y-%m-%d %H:%M:%S")}')
- # 注意,这里取到的数据未复权
- latest_price = ContextInfo.get_market_data_ex(
- fields=['close'], period='follow', count=1,
- stock_code=[trade.stock_code],
- end_time=timetag_to_datetime(timetag, "%Y%m%d%H%M%S"),
- dividend_type='none',
- )[trade.stock_code].iloc[0, 0]
- logging.info(f'最新股价: {latest_price}')
- balance, cash = list(map(sum, zip(*list(
- (account.m_dBalance, account.m_dAvailable)
- for account in get_trade_detail_data(trade.account_id, 'STOCK', 'ACCOUNT')
- ))))
- logging.info(f'总资产: {balance} 元, 现金: {cash} 元')
- # 持仓数据
- positions = get_trade_detail_data(trade.account_id, 'STOCK', 'POSITION')
- holdings = sum(p.m_nVolume for p in positions)
- free_holdings = sum(p.m_nYesterdayVolume for p in positions)
- logging.info(f'持仓: {holdings} 股, 其中 {free_holdings} 股可卖')
- price = 13.70
- volume = 100
- if holdings < 100:
- passorder(
- 23, # opType, 买入股票
- 1101, # orderType, 单股、单账号、普通、股/手方式下单
- trade.account_id, # accountID
- trade.stock_code, # orderCode
- 11, # prType, 指定价
- price, # price
- volume, # volume
- '', # strategyName
- 1, # quickTrade,
- '', # userOrderId
- ContextInfo,
- )
- logging.info(f'发出建仓单, {price} 元 x {volume} 股')
复制代码
测试标的: 国泰君安 601211
开始时间: 2024-04-01 09:30:00
结束时间: 2024-04-10 15:00:00
复权方式:不复权
默认周期:3分钟
其他参数取默认值,对结果没有太大影响。
下面是日志开头的一部分:
- 【2024-05-13 22:10:06.773】 start back test mode
- 【2024-05-13 22:10:06.914】 INFO:root:bar: 2024-04-01 09:33:00
- 【2024-05-13 22:10:06.977】 INFO:root:最新股价: 13.98
- 【2024-05-13 22:10:06.978】 INFO:root:总资产: 100000.0 元, 现金: 100000.0 元
- 【2024-05-13 22:10:06.978】 INFO:root:持仓: 0 股, 其中 0 股可卖
- 【2024-05-13 22:10:06.990】 [系统]WARNING:指定价13.7不在当前周期最低最高价间[13.89,14.03],使用最新价13.98, 代码:601211.SH, 日期时间 : 20240401 09:33:00
- 【2024-05-13 22:10:06.990】 INFO:root:发出建仓单, 13.7 元 x 100 股
- 【2024-05-13 22:10:07.013】 INFO:root:bar: 2024-04-01 09:36:00
- 【2024-05-13 22:10:07.013】 INFO:root:最新股价: 13.95
- 【2024-05-13 22:10:07.013】 INFO:root:总资产: 99997.0 元, 现金: 98602.0 元
- 【2024-05-13 22:10:07.013】 INFO:root:持仓: 100 股, 其中 0 股可卖
- 【2024-05-13 22:10:07.013】 INFO:root:bar: 2024-04-01 09:39:00
- 【2024-05-13 22:10:07.016】 INFO:root:最新股价: 13.95
- 【2024-05-13 22:10:07.017】 INFO:root:总资产: 99997.0 元, 现金: 98602.0 元
- 【2024-05-13 22:10:07.018】 INFO:root:持仓: 100 股, 其中 0 股可卖
复制代码
|