增加交易策略、交易指标、量化库代码等文件夹
This commit is contained in:
144
1.交易策略/1.CTA策略/2.VeighNa策略/1.atr_rsi_strategy.py
Normal file
144
1.交易策略/1.CTA策略/2.VeighNa策略/1.atr_rsi_strategy.py
Normal file
@@ -0,0 +1,144 @@
|
||||
from vnpy_ctastrategy import (
|
||||
CtaTemplate,
|
||||
StopOrder,
|
||||
TickData,
|
||||
BarData,
|
||||
TradeData,
|
||||
OrderData,
|
||||
BarGenerator,
|
||||
ArrayManager,
|
||||
)
|
||||
|
||||
|
||||
class AtrRsiStrategy(CtaTemplate):
|
||||
""""""
|
||||
|
||||
author = "用Python的交易员"
|
||||
|
||||
atr_length = 22
|
||||
atr_ma_length = 10
|
||||
rsi_length = 5
|
||||
rsi_entry = 16
|
||||
trailing_percent = 0.8
|
||||
fixed_size = 1
|
||||
|
||||
atr_value = 0
|
||||
atr_ma = 0
|
||||
rsi_value = 0
|
||||
rsi_buy = 0
|
||||
rsi_sell = 0
|
||||
intra_trade_high = 0
|
||||
intra_trade_low = 0
|
||||
|
||||
parameters = [
|
||||
"atr_length",
|
||||
"atr_ma_length",
|
||||
"rsi_length",
|
||||
"rsi_entry",
|
||||
"trailing_percent",
|
||||
"fixed_size",
|
||||
]
|
||||
variables = [
|
||||
"atr_value",
|
||||
"atr_ma",
|
||||
"rsi_value",
|
||||
"rsi_buy",
|
||||
"rsi_sell",
|
||||
"intra_trade_high",
|
||||
"intra_trade_low",
|
||||
]
|
||||
|
||||
def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
|
||||
""""""
|
||||
super().__init__(cta_engine, strategy_name, vt_symbol, setting)
|
||||
self.bg = BarGenerator(self.on_bar)
|
||||
self.am = ArrayManager()
|
||||
|
||||
def on_init(self):
|
||||
"""
|
||||
Callback when strategy is inited.
|
||||
"""
|
||||
self.write_log("策略初始化")
|
||||
|
||||
self.rsi_buy = 50 + self.rsi_entry
|
||||
self.rsi_sell = 50 - self.rsi_entry
|
||||
|
||||
self.load_bar(10)
|
||||
|
||||
def on_start(self):
|
||||
"""
|
||||
Callback when strategy is started.
|
||||
"""
|
||||
self.write_log("策略启动")
|
||||
|
||||
def on_stop(self):
|
||||
"""
|
||||
Callback when strategy is stopped.
|
||||
"""
|
||||
self.write_log("策略停止")
|
||||
|
||||
def on_tick(self, tick: TickData):
|
||||
"""
|
||||
Callback of new tick data update.
|
||||
"""
|
||||
self.bg.update_tick(tick)
|
||||
|
||||
def on_bar(self, bar: BarData):
|
||||
"""
|
||||
Callback of new bar data update.
|
||||
"""
|
||||
self.cancel_all()
|
||||
|
||||
am = self.am
|
||||
am.update_bar(bar)
|
||||
if not am.inited:
|
||||
return
|
||||
|
||||
atr_array = am.atr(self.atr_length, array=True)
|
||||
self.atr_value = atr_array[-1]
|
||||
self.atr_ma = atr_array[-self.atr_ma_length :].mean()
|
||||
self.rsi_value = am.rsi(self.rsi_length)
|
||||
|
||||
if self.pos == 0:
|
||||
self.intra_trade_high = bar.high_price
|
||||
self.intra_trade_low = bar.low_price
|
||||
|
||||
if self.atr_value > self.atr_ma:
|
||||
if self.rsi_value > self.rsi_buy:
|
||||
self.buy(bar.close_price + 5, self.fixed_size)
|
||||
elif self.rsi_value < self.rsi_sell:
|
||||
self.short(bar.close_price - 5, self.fixed_size)
|
||||
|
||||
elif self.pos > 0:
|
||||
self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
|
||||
self.intra_trade_low = bar.low_price
|
||||
|
||||
long_stop = self.intra_trade_high * (1 - self.trailing_percent / 100)
|
||||
self.sell(long_stop, abs(self.pos), stop=True)
|
||||
|
||||
elif self.pos < 0:
|
||||
self.intra_trade_low = min(self.intra_trade_low, bar.low_price)
|
||||
self.intra_trade_high = bar.high_price
|
||||
|
||||
short_stop = self.intra_trade_low * (1 + self.trailing_percent / 100)
|
||||
self.cover(short_stop, abs(self.pos), stop=True)
|
||||
|
||||
self.put_event()
|
||||
|
||||
def on_order(self, order: OrderData):
|
||||
"""
|
||||
Callback of new order data update.
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_trade(self, trade: TradeData):
|
||||
"""
|
||||
Callback of new trade data update.
|
||||
"""
|
||||
self.put_event()
|
||||
|
||||
def on_stop_order(self, stop_order: StopOrder):
|
||||
"""
|
||||
Callback of stop order update.
|
||||
"""
|
||||
pass
|
||||
114
1.交易策略/1.CTA策略/2.VeighNa策略/Y03 基于布林带的股票量化择时策略/布林策略.py
Normal file
114
1.交易策略/1.CTA策略/2.VeighNa策略/Y03 基于布林带的股票量化择时策略/布林策略.py
Normal file
@@ -0,0 +1,114 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from pandas import Series,DataFrame
|
||||
|
||||
def initialize(context):
|
||||
# 设定沪深300作为基准
|
||||
set_benchmark('000300.XSHG')
|
||||
# 开启动态复权模式(真实价格)
|
||||
set_option('use_real_price', True)
|
||||
# 股票类交易手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱
|
||||
set_order_cost(OrderCost(open_tax=0, close_tax=0.001, \
|
||||
open_commission=0.0003, close_commission=0.0003,\
|
||||
close_today_commission=0, min_commission=5), type='stock')
|
||||
def handle_data(context, data):
|
||||
#获取沪深300股票池
|
||||
stock_set=get_index_stocks('000300.XSHG')
|
||||
#此处可增加选股条件
|
||||
q = query(
|
||||
valuation.code, # 股票代码
|
||||
).filter(
|
||||
valuation.code.in_(stock_set),#只对设定股票池执行
|
||||
)
|
||||
#获取财务数据,指定日期为回测当天
|
||||
current_date=context.current_dt.strftime('%Y-%m-%d')
|
||||
fdf = get_fundamentals(q,current_date)
|
||||
#取前50只股
|
||||
fdf=fdf.head(100)
|
||||
#获取股票列表
|
||||
get_stocks=list(fdf['code'])
|
||||
# 去除ST,*ST
|
||||
st=get_extras('is_st',get_stocks,current_date,current_date, df=True)
|
||||
st=st.loc[current_date]
|
||||
get_stocks=list(st[st==False].index)
|
||||
#考虑5天的历史数据
|
||||
num=5
|
||||
#轨线用前面20天数据计算
|
||||
days=20
|
||||
#每只股票可用资金为当前资金除以50
|
||||
cash=context.portfolio.available_cash/100
|
||||
#获取所有股票前num+days天收盘价数据
|
||||
price=history(num+days,'1d','close',get_stocks,skip_paused=True)
|
||||
where_are_nan = np.isnan(price)
|
||||
where_are_inf = np.isinf(price)
|
||||
price[where_are_nan] = 0
|
||||
price[where_are_inf] = 0
|
||||
#循环每只股
|
||||
for security in get_stocks:
|
||||
#用数组保存均值,大小为num
|
||||
mid=np.arange(num)
|
||||
#标准差
|
||||
std=np.arange(num)
|
||||
#定义数组大小
|
||||
close_data=np.arange(num*days).reshape(num,days)
|
||||
for i in range(0,num):
|
||||
for j in range(0,days):
|
||||
close_data[i][j]=price[security][i+j]
|
||||
#中轨线即均值为days天收盘价数据平均
|
||||
mid[i]=np.mean(close_data[i])
|
||||
#计算标准差
|
||||
std[i]=np.std(close_data[i])
|
||||
#上轨线=中轨线+两倍的标准差
|
||||
up=mid[num-1]+2*std[num-1]
|
||||
#下轨线
|
||||
down=mid[num-1]-2*std[num-1]
|
||||
#保存num天数据,判断开口收口或平口
|
||||
boll=0
|
||||
for i in range(0,num-1):
|
||||
if std[i]>std[i+1]:
|
||||
boll=boll+1
|
||||
else:
|
||||
boll=boll-1
|
||||
|
||||
#判断目前股票是否停牌
|
||||
paused=data[security].paused
|
||||
|
||||
#取得当前股票价格
|
||||
current_price=data[security].price
|
||||
#如果连续num天开口
|
||||
if boll==-4:
|
||||
#如果当前价格超过昨日的上轨且价格高于均线
|
||||
if current_price>up and current_price>mid[num-1]:
|
||||
#计算可以买多少股票
|
||||
num_of_shares=int(cash/current_price)
|
||||
#如果可以买的数量超过0并且股票未停牌
|
||||
if num_of_shares>0 and paused==False:
|
||||
#购买股票
|
||||
order(security,+num_of_shares)
|
||||
#如果当前价格跌破了昨日的下轨且价格低于均线
|
||||
elif current_price<down and current_price<mid[num-1]:
|
||||
#如果股票未停牌
|
||||
if paused==False:
|
||||
#将股票卖空
|
||||
order_target(security,0)
|
||||
#如果连续num天收口
|
||||
if boll==4:
|
||||
#股价超过上轨且价格低于均线时卖
|
||||
if current_price>up and current_price<mid[num-1]:
|
||||
if paused==False:
|
||||
order_target(security,0)
|
||||
#跌破下轨且价格高于均线时买
|
||||
elif current_price<down and current_price>mid[num-1]:
|
||||
num_of_shares=int(cash/current_price)
|
||||
if num_of_shares>0 and paused==False:
|
||||
order(security,+num_of_shares)
|
||||
#连续平口
|
||||
if boll in range(-1,1):
|
||||
#价格在中轨线上且昨日均价高于三天前
|
||||
if current_price>mid[num-1] and mid[num-1]>mid[num-3]:
|
||||
num_of_shares=int(cash/current_price)
|
||||
if num_of_shares>0 and paused==False:
|
||||
order(security,+num_of_shares)
|
||||
if current_price<mid[num-1] and mid[num-1]<mid[num-3]:
|
||||
if paused==False:
|
||||
order_target(security,0)
|
||||
BIN
1.交易策略/1.CTA策略/2.VeighNa策略/Y03 基于布林带的股票量化择时策略/布林策略研究报告.pdf
Normal file
BIN
1.交易策略/1.CTA策略/2.VeighNa策略/Y03 基于布林带的股票量化择时策略/布林策略研究报告.pdf
Normal file
Binary file not shown.
BIN
1.交易策略/1.CTA策略/2.VeighNa策略/Y03 基于布林带的股票量化择时策略/策略加载说明.docx
Normal file
BIN
1.交易策略/1.CTA策略/2.VeighNa策略/Y03 基于布林带的股票量化择时策略/策略加载说明.docx
Normal file
Binary file not shown.
BIN
1.交易策略/1.CTA策略/2.VeighNa策略/Y04 基于趋势判断的股票量化择时策略/Y04趋势择时策略研究报告.pdf
Normal file
BIN
1.交易策略/1.CTA策略/2.VeighNa策略/Y04 基于趋势判断的股票量化择时策略/Y04趋势择时策略研究报告.pdf
Normal file
Binary file not shown.
BIN
1.交易策略/1.CTA策略/2.VeighNa策略/Y04 基于趋势判断的股票量化择时策略/策略加载说明.docx
Normal file
BIN
1.交易策略/1.CTA策略/2.VeighNa策略/Y04 基于趋势判断的股票量化择时策略/策略加载说明.docx
Normal file
Binary file not shown.
97
1.交易策略/1.CTA策略/2.VeighNa策略/Y04 基于趋势判断的股票量化择时策略/趋势择时策略.py
Normal file
97
1.交易策略/1.CTA策略/2.VeighNa策略/Y04 基于趋势判断的股票量化择时策略/趋势择时策略.py
Normal file
@@ -0,0 +1,97 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
# In[ ]:
|
||||
|
||||
# 导入函数库
|
||||
import jqdata
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
|
||||
# 初始化函数,设定基准等等
|
||||
def initialize(context):
|
||||
# 设定沪深300作为基准
|
||||
set_benchmark('000300.XSHG')
|
||||
# 开启动态复权模式(真实价格)
|
||||
set_option('use_real_price', True)
|
||||
# 股票类每笔交易时的手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱
|
||||
set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
|
||||
|
||||
#获取沪深300股票池
|
||||
stock_set=get_index_stocks('000300.XSHG')
|
||||
#此处可增加选股条件
|
||||
q = query(
|
||||
valuation.code, # 股票代码
|
||||
).filter(
|
||||
valuation.code.in_(stock_set),#只对设定股票池执行
|
||||
)
|
||||
fdf = get_fundamentals(q)
|
||||
#取前50只股
|
||||
fdf=fdf.head(50)
|
||||
#获取股票列表
|
||||
stock_list=list(fdf['code'])
|
||||
trend={}
|
||||
for security in stock_list:
|
||||
trend[security]='None'
|
||||
|
||||
def handle_data(context, data):
|
||||
N = 20 # 计算TR时的N
|
||||
M = 49 # 计算MATRIX时的M
|
||||
num=3
|
||||
length_of_data = N+M+num # 取closeprice的天数,为了足够计算MATRIX、TRIX
|
||||
|
||||
cash=context.portfolio.available_cash/50
|
||||
for security in stock_list:
|
||||
close_price=attribute_history(security,length_of_data,'1d',('close'),skip_paused=True)
|
||||
where_are_nan = np.isnan(close_price)
|
||||
where_are_inf = np.isinf(close_price)
|
||||
close_price[where_are_nan] = 0
|
||||
close_price[where_are_inf] = 0
|
||||
|
||||
MA5=close_price['close'][-5:].mean()
|
||||
MA10=close_price['close'][-10:].mean()
|
||||
ma5=close_price['close'][-6:-1].mean()
|
||||
ma10=close_price['close'][-11:-1].mean()
|
||||
|
||||
price_array={}
|
||||
for i in range(0,M+num):
|
||||
price_array[i]=close_price['close'][i:i+N]
|
||||
#TR=收盘价的N日指数移动平均
|
||||
TR={}
|
||||
for i in range(0,M+num):
|
||||
TR[i]=np.mean(price_array[i])
|
||||
#TRIX=(TR-昨日TR)/昨日TR*100
|
||||
TRIX={}
|
||||
for i in range(1,M+num):
|
||||
if TR[i]==0:
|
||||
TRIX[i]=0
|
||||
continue
|
||||
TRIX[i]=(TR[i]-TR[i-1])/TR[i]*100
|
||||
#MATRIX=TRIX的M日简单移动平均
|
||||
MATRIX={}
|
||||
for i in range(0,num):
|
||||
TRIX_sum=0
|
||||
for j in range(1,M):
|
||||
TRIX_sum=TRIX_sum+TRIX[i+j]
|
||||
MATRIX[i]=TRIX_sum/M
|
||||
current_price=data[security].price
|
||||
|
||||
length=0
|
||||
for i in range(0,num-1):
|
||||
if TRIX[M+i]>MATRIX[i]:
|
||||
length=length+1
|
||||
else:
|
||||
length=length-1
|
||||
if length>0 and MATRIX[num-1]>MATRIX[0]:
|
||||
trend[security]='up'
|
||||
elif length<0 and MATRIX[num-1]<MATRIX[0]:
|
||||
trend[security]='down'
|
||||
|
||||
if trend[security]=='up':
|
||||
order_value(security,cash)
|
||||
elif trend[security]=='down' and security in context.portfolio.positions:
|
||||
if MA5<MA10:
|
||||
order_target(security,0)
|
||||
elif MA5>MA10 and ma5<ma10 :
|
||||
order_value(security,cash)
|
||||
|
||||
Reference in New Issue
Block a user