# 导入库包 import talib import numpy as np import pandas as pd # 初始化证券账户及策略信息 def init(context): # 设置要交易的股票池 context.stk = '000002.SZ' # 设置参照基准 set_benchmark(context.stk) # 设置获取历史数据的时间周期 g.period = 10 # 该函数用来定时执行买卖条件,每个交易频率(日/分钟)自动调用一次. def handle_bar(context, bar_dict): # 获取过去g.period天的历史行情数据 price = history(context.stk, ['close','high','low'], g.period, '1d', False, 'pre', is_panel=0) # 获取收盘价数据 close = price['close'].values # 计算SMA SMA = talib.SMA(close,g.period) # 获取当前的股票价格 crtprice = bar_dict[context.stk].open # 获取当前个股的持仓 curposition = context.portfolio.positions[context.stk].amount # 若开盘价上穿均线,且持仓为0,则全仓买入 if crtprice > SMA[-1] and curposition == 0: order_target_percent(context.stk,1) print('买入价格:'+str(crtprice)) # 若开盘价下穿均线,且有持仓,则清仓 if crtprice < SMA[-1] and curposition !=0: order_target_percent(context.stk,0) print('卖出价格:'+str(crtprice)) # 绘图 record(SMA
时间: 2024-04-27 17:22:57 浏览: 231
这代码使用了Python的量化交易框架vnpy,并结合talib库计算了股票的SMA指标,并根据该指标的上下穿透情况,判断买入或卖出信号,并执行交易操作。具体来说,init函数用于初始化证券账户及策略信息,包括设置要交易的股票池、参照基准、获取历史数据的时间周期等。handle_bar函数用于定时执行买卖条件,获取过去g.period天的历史行情数据,并计算SMA指标,判断买卖信号并执行交易操作。最后,该代码还使用了record函数绘制SMA指标的曲线图。
相关问题
import pandas as pdimport numpy as npimport talibimport tushare as ts# 先写出回测框架class Backtest(): def __init__(self, data, init_balance): self.data = data self.init_balance = init_balance self.position = 0 self.balance = init_balance self.equity = 0 def update_balance(self, price): self.equity = self.position * price self.balance = self.balance + self.equity def run(self, strategy): for i in range(1, len(self.data)): signal = strategy.generate_signal(self.data.iloc[:i, :]) price = self.data.iloc[i, 0] # 按照信号来调整持仓 if signal == 1: self.position = np.floor(self.balance / price) # 买入所有可用资金 elif signal == -1: self.position = 0 # 卖出所有股票 self.update_balance(price) print("日期:", self.data.index[i], "价格:", price, "信号:", signal, "账户价值:", self.balance) # 输出最后的回测结果 print("回测结果: 最开始的账户余额为", self.init_balance, ",最终的账户余额为", self.balance, ",因此您的盈亏为", self.balance-self.init_balance)# 再写出策略类class MACD_Strategy(): def __init__(self, fast_period, slow_period, signal_period): self.fast_period = fast_period self.slow_period = slow_period self.signal_period = signal_period def generate_signal(self, data): macd, signal, hist = talib.MACD(data["close"], fastperiod=self.fast_period, slowperiod=self.slow_period, signalperiod=self.signal_period) if hist[-1] > 0 and hist[-2] < 0: return 1 # 金叉,买入 elif hist[-1] < 0 and hist[-2] > 0: return -1 # 死叉,卖出 else: return 0 # 无操作# 最后的主程序if __name__ == "__main__": # 下载数据 data = ts.get_hist_data("600000", start="2020-01-01", end="2021-01-01") data = data.sort_index() # 按日期排序 data = data.loc[:, ["open", "high", "close", "low", "volume"]] # 只保留这五列 data.index = pd.to_datetime(data.index) # 初始化回测 backtest = Backtest(data, init_balance=100000) # 初始化策略 strategy = MACD_Strategy(fast_period=12, slow_period=26, signal_period=9) # 运行回测 backtest.run(strategy)
这是一段Python代码,用于导入Pandas、Numpy、Talib以及Tushare这几个Python库。Pandas和Numpy是用于数据处理的库,Talib是用于技术指标计算的库,Tushare是用于获取股市数据的库。
#encoding:gbk import pandas as pd import numpy as np import talib import datetime import time import sys sys.path.append(r'D:\国信\国信iQuant策略交易平台\bin.x64\Lib\site-packages') import pymysql stocklist = ['002587.SZ', '300548.SZ', '301046.SZ', '001287.SZ', '300052.SZ', '300603.SZ', '300926.SZ', '300605.SZ', '300826.SZ', '301049.SZ'] def init(ContextInfo): ContextInfo.accID = "410001212417" #str(account) 交易帐号 ContextInfo.buy = True ContextInfo.sell = False today = datetime.datetime.now().strftime('%Y-%m-%d') #定义时间 order_time = today + ' 19:06:30' #定义时间 买股票 ContextInfo.run_time("myHandlebar", '1nDay', order_time, "SZ") #一天执行一次定义的myHandlebar def myHandlebar(ContextInfo): try: db = pymysql.connect(host='127.0.0.1', user='user', password='123456', db='python') print('数据库连接成功') except pymysql.Error as e: print('数据库连接失败') def get_stock_data(stock): G1 = ContextInfo.get_full_tick([stock]) # 获取分笔数据 G2 = [stock, G1[stock]['lastPrice'], G1[stock]['lastClose'], G1[stock]['pvolume']] # 最新 收盘 成交量 G3 = ContextInfo.get_last_volume(stock) # 总流通股 G4 = ContextInfo.get_instrumentdetail(stock) # 财表 G5 = [G4['TotalVolumn']] # 总股本 S1 = [G2[1] / G2[2] * 100 - 100] #涨幅 S2 = [G2[3] / G3 * 100] #换手率 S3 = [G2[1] * item for item in G5] #总市值 return [S1, S2, S3] stock_data = {} for stock in stocklist: stock_data[stock] = get_stock_data(stock) print(stock_data) 我打代码是这样,打印出来的结果是:{'002587.SZ': [[1.0479041916167802], [1.9914331748339686], [4397895000.0]], '300548.SZ': [[-3.7646314457450103], [9.90358201249419], [8700728400.0]], '301046.SZ': [[1.8993668777074362], [2.722894468951476], [4577520200.0]], '001287.SZ': [[0.9848484848484986], [4.357778802843653], [20258934000.0]], '300052.SZ': [[0.16330974414806576], [1.3332567665862716], [4818040000.000001]], '300603.SZ': [[0.3496503496503607], [1.4677953941892266], [5335789200.0]], '300926.SZ': [[-0.25839793281653556], [6.75514802163393], [6457471200.0]], '300605.SZ': [[-0.13888888888888573], [1.495405645304456], [2364934800.0]], '300826.SZ': [[8.338480543545373], [15.573514174701398], [2553824000.0]], '301049.SZ': [[-8.936698386429455], [19.581253894080998], [2074442500.0000002]]},在这代码的基础上,帮我把其中的'002587.SZ'对应的数值打印出来
当你想要打印出`'002587.SZ'`对应的数值时,你可以使用以下代码:
```python
stock_data = {
'002587.SZ': [[1.0479041916167802], [1.9914331748339686], [4397895000.0]],
'300548.SZ': [[-3.7646314457450103], [9.90358201249419], [8700728400.0]],
'301046.SZ': [[1.8993668777074362], [2.722894468951476], [4577520200.0]],
'001287.SZ': [[0.9848484848484986], [4.357778802843653], [20258934000.0]],
'300052.SZ': [[0.16330974414806576], [1.3332567665862716], [4818040000.000001]],
'300603.SZ': [[0.3496503496503607], [1.4677953941892266], [5335789200.0]],
'300926.SZ': [[-0.25839793281653556], [6.75514802163393], [6457471200.0]],
'300605.SZ': [[-0.13888888888888573], [1.495405645304456], [2364934800.0]],
'300826.SZ': [[8.338480543545373], [15.573514174701398], [2553824000.0]],
'301049.SZ': [[-8.936698386429455], [19.581253894080998], [2074442500.0000002]]
}
data = stock_data['002587.SZ']
print(data)
```
运行这段代码,你将会得到`'002587.SZ'`对应的数值`[[1.0479041916167802], [1.9914331748339686], [4397895000.0]]`的输出结果。
阅读全文