策略化#13,#15,#16,#44,#83号因子

This commit is contained in:
Harvey-Sun
2017-03-06 17:58:04 +08:00
parent 45d55224e8
commit 589bb39dd6
35 changed files with 444 additions and 18 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

+139
View File
@@ -0,0 +1,139 @@
# -*- coding:utf-8 -*-
from CloudQuant import MiniSimulator
import numpy as np
import pandas as pd
username = 'Harvey_Sun'
password = 'P948894dgmcsy'
Strategy_Name = 'WQ_alpha#015_20_100'
INIT_CAP = 100000000
START_DATE = '20130101'
END_DATE = '20161231'
Fee_Rate = 0.001
program_path = 'C:/cStrategy/'
buy_number = 100
period = 20
s_or_b = False # true表示选因子较小的股票,false表示选因子较大的股票
def correlation(x, y):
upside = ((x - x.mean()) * (y - y.mean())).sum(skipna=False)
dnside = x.std() * y.std()
result = upside / dnside
return result
def initial(sdk):
sdk.prepareData(['LZ_GPA_QUOTE_THIGH', 'LZ_GPA_QUOTE_TVOLUME',
'LZ_GPA_CMFTR_CUM_FACTOR', 'LZ_GPA_SLCIND_STOP_FLAG'])
stock_pool = []
sdk.setGlobal('stock_pool', stock_pool)
step = period
sdk.setGlobal('step', step)
def init_per_day(sdk):
step = sdk.getGlobal('step')
if step == period:
stock_list = sdk.getStockList()
high = pd.DataFrame(sdk.getFieldData('LZ_GPA_QUOTE_THIGH')[-5:], columns=stock_list)
volume = pd.DataFrame(sdk.getFieldData('LZ_GPA_QUOTE_TVOLUME')[-5:], columns=stock_list)
adj_f = pd.DataFrame(sdk.getFieldData('LZ_GPA_CMFTR_CUM_FACTOR')[-5:], columns=stock_list)
stop = pd.DataFrame(sdk.getFieldData('LZ_GPA_SLCIND_STOP_FLAG')[-6:], columns=stock_list)
volume.replace(0, np.nan, inplace=True)
adj_high = high * adj_f
adj_volume = volume / adj_f
# 计算昨天的factor
high_rank = adj_high.rank(axis=1, pct=True)
volume_rank = adj_volume.rank(axis=1, pct=True)
factor = pd.DataFrame(index=stock_list)
for i in [0, 1, 2]:
temp = correlation(high_rank[i:i+3], volume_rank[i:i+3])
factor[i] = temp
factor = -1 * factor.T.sum(axis=0, skipna=False)
# 选出排序靠前的股票
factor[stop.notnull().any()] = np.nan # 剔除停牌的股票
factor.sort_values(ascending=s_or_b, inplace=True)
stock_pool = factor.index[:buy_number]
# 选出当天应该调仓的股票
position = sdk.getPositions()
position_dict = dict([i.code, i.optPosition] for i in position)
stock_to_buy = set(stock_pool) - set(position_dict.keys())
stock_to_sell = set(position_dict.keys()) - set(stock_pool)
sdk.setGlobal('position_dict', position_dict)
sdk.setGlobal('stock_to_buy', stock_to_buy)
sdk.setGlobal('stock_to_sell', stock_to_sell)
else:
pass
def strategy(sdk):
step = sdk.getGlobal('step')
if step == period:
step = 1
today = sdk.getNowDate()
sdk.sdklog(today,'====================')
position_dict = sdk.getGlobal('position_dict')
stock_to_buy = sdk.getGlobal('stock_to_buy')
stock_to_sell = sdk.getGlobal('stock_to_sell')
quotes = sdk.getQuotes(list(stock_to_buy | stock_to_sell))
sell_orders = []
for stock in stock_to_sell:
if stock in quotes.keys():
price = quotes[stock].open
volume = position_dict[stock]
order = [stock, price, volume, -1]
sell_orders.append(order)
if sell_orders:
sdk.makeOrders(sell_orders)
sdk.sdklog('===sell orders===')
sdk.sdklog(np.array(sell_orders))
available_cash = sdk.getAccountInfo().availableCash
available_cash_one_stock = available_cash / len(stock_to_buy)
buy_orders = []
for stock in stock_to_buy:
if stock in quotes.keys():
price = quotes[stock].open
volume = int(available_cash_one_stock / (price * 100)) * 100
if volume > 0:
order = [stock, price, volume, 1]
buy_orders.append(order)
if buy_orders:
sdk.makeOrders(buy_orders)
sdk.sdklog('===buy orders===')
sdk.sdklog(np.array(buy_orders))
else:
step += 1
sdk.setGlobal('step', step)
config = {
'username': username,
'password': password,
'initCapital': INIT_CAP,
'startDate': START_DATE,
'endDate': END_DATE,
'strategy': strategy,
'initial': initial,
'preparePerDay': init_per_day,
'feeRate': Fee_Rate,
'strategyName': Strategy_Name,
'logfile': '%s.log' % Strategy_Name,
'rootpath': program_path,
'executeMode': 'D',
'feeLimit': 5,
'cycle': 10,
'dealByVolume': True,
'allowForTodayFactors': ['LZ_GPA_SLCIND_STOP_FLAG']
}
if __name__ == "__main__":
# 在线运行所需代码
import os
config['strategyID'] = os.path.splitext(os.path.split(__file__)[1])[0]
MiniSimulator(**config).run()
+136
View File
@@ -0,0 +1,136 @@
# -*- coding:utf-8 -*-
from CloudQuant import MiniSimulator
import numpy as np
import pandas as pd
username = 'Harvey_Sun'
password = 'P948894dgmcsy'
Strategy_Name = 'WQ_alpha#016_10_100'
INIT_CAP = 100000000
START_DATE = '20130101'
END_DATE = '20161231'
Fee_Rate = 0.001
program_path = 'C:/cStrategy/'
buy_number = 100
period = 10
s_or_b = False # true表示选因子较小的股票,false表示选因子较大的股票
def correlation(x, y):
upside = ((x - x.mean()) * (y - y.mean())).sum(skipna=False)
dnside = x.std() * y.std()
result = upside / dnside
return result
def initial(sdk):
sdk.prepareData(['LZ_GPA_QUOTE_THIGH', 'LZ_GPA_QUOTE_TVOLUME',
'LZ_GPA_CMFTR_CUM_FACTOR', 'LZ_GPA_SLCIND_STOP_FLAG'])
stock_pool = []
sdk.setGlobal('stock_pool', stock_pool)
step = period
sdk.setGlobal('step', step)
def init_per_day(sdk):
step = sdk.getGlobal('step')
if step == period:
stock_list = sdk.getStockList()
high = pd.DataFrame(sdk.getFieldData('LZ_GPA_QUOTE_THIGH')[-5:], columns=stock_list)
volume = pd.DataFrame(sdk.getFieldData('LZ_GPA_QUOTE_TVOLUME')[-5:], columns=stock_list)
adj_f = pd.DataFrame(sdk.getFieldData('LZ_GPA_CMFTR_CUM_FACTOR')[-5:], columns=stock_list)
stop = pd.DataFrame(sdk.getFieldData('LZ_GPA_SLCIND_STOP_FLAG')[-6:], columns=stock_list)
volume.replace(0, np.nan, inplace=True)
adj_high = high * adj_f
adj_volume = volume / adj_f
# 计算昨天的factor
high_rank = adj_high.rank(axis=1, pct=True)
volume_rank = adj_volume.rank(axis=1, pct=True)
factor = -1 * ((high_rank - high_rank.mean()) * (volume_rank - volume_rank.mean())).sum(skipna=False).rank(
pct=True)
# 选出排序靠前的股票
factor[stop.notnull().any()] = np.nan # 剔除停牌的股票
factor.sort_values(ascending=s_or_b, inplace=True)
stock_pool = factor.index[:buy_number]
# 选出当天应该调仓的股票
position = sdk.getPositions()
position_dict = dict([i.code, i.optPosition] for i in position)
stock_to_buy = set(stock_pool) - set(position_dict.keys())
stock_to_sell = set(position_dict.keys()) - set(stock_pool)
sdk.setGlobal('position_dict', position_dict)
sdk.setGlobal('stock_to_buy', stock_to_buy)
sdk.setGlobal('stock_to_sell', stock_to_sell)
else:
pass
def strategy(sdk):
step = sdk.getGlobal('step')
if step == period:
step = 1
today = sdk.getNowDate()
sdk.sdklog(today,'====================')
position_dict = sdk.getGlobal('position_dict')
stock_to_buy = sdk.getGlobal('stock_to_buy')
stock_to_sell = sdk.getGlobal('stock_to_sell')
quotes = sdk.getQuotes(list(stock_to_buy | stock_to_sell))
sell_orders = []
for stock in stock_to_sell:
if stock in quotes.keys():
price = quotes[stock].open
volume = position_dict[stock]
order = [stock, price, volume, -1]
sell_orders.append(order)
if sell_orders:
sdk.makeOrders(sell_orders)
sdk.sdklog('===sell orders===')
sdk.sdklog(np.array(sell_orders))
available_cash = sdk.getAccountInfo().availableCash
available_cash_one_stock = available_cash / len(stock_to_buy)
buy_orders = []
for stock in stock_to_buy:
if stock in quotes.keys():
price = quotes[stock].open
volume = int(available_cash_one_stock / (price * 100)) * 100
if volume > 0:
order = [stock, price, volume, 1]
buy_orders.append(order)
if buy_orders:
sdk.makeOrders(buy_orders)
sdk.sdklog('===buy orders===')
sdk.sdklog(np.array(buy_orders))
else:
step += 1
sdk.setGlobal('step', step)
config = {
'username': username,
'password': password,
'initCapital': INIT_CAP,
'startDate': START_DATE,
'endDate': END_DATE,
'strategy': strategy,
'initial': initial,
'preparePerDay': init_per_day,
'feeRate': Fee_Rate,
'strategyName': Strategy_Name,
'logfile': '%s.log' % Strategy_Name,
'rootpath': program_path,
'executeMode': 'D',
'feeLimit': 5,
'cycle': 10,
'dealByVolume': True,
'allowForTodayFactors': ['LZ_GPA_SLCIND_STOP_FLAG']
}
if __name__ == "__main__":
# 在线运行所需代码
import os
config['strategyID'] = os.path.splitext(os.path.split(__file__)[1])[0]
MiniSimulator(**config).run()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

+17 -12
View File
@@ -6,7 +6,7 @@ import pandas as pd
username = 'Harvey_Sun'
password = 'P948894dgmcsy'
Strategy_Name = 'WQ_alpha#044_10_100'
Strategy_Name = 'WQ_alpha#044_20_100'
INIT_CAP = 100000000
START_DATE = '20130101'
@@ -14,8 +14,15 @@ END_DATE = '20161231'
Fee_Rate = 0.001
program_path = 'C:/cStrategy/'
buy_number = 100
period = 10
lowest = False # 是否选因子值最小的股票,False为选取因子最大的股票
period = 20
s_or_b = False # true表示选因子较小的股票,false表示选因子较大的股票
def correlation(x, y):
upside = ((x - x.mean()) * (y - y.mean())).sum(skipna=False)
dnside = x.std() * y.std()
result = upside / dnside
return result
def initial(sdk):
@@ -35,19 +42,17 @@ def init_per_day(sdk):
volume = pd.DataFrame(sdk.getFieldData('LZ_GPA_QUOTE_TVOLUME')[-5:], columns=stock_list)
adj_f = pd.DataFrame(sdk.getFieldData('LZ_GPA_CMFTR_CUM_FACTOR')[-5:], columns=stock_list)
stop = pd.DataFrame(sdk.getFieldData('LZ_GPA_SLCIND_STOP_FLAG')[-6:], columns=stock_list)
volume.replace(0, np.nan, inplace=True)
adj_high = high * adj_f
adj_volume = volume / adj_f
# 计算昨天的factor
volume_rank = adj_volume.rank(axis=1, pct=True)
factor = {}
for i in adj_high.columns:
factor[i] = pd.concat([adj_high[i], volume_rank[i]], axis=1).corr().iloc[0,1]
factor = pd.Series(factor)
factor = -1 * correlation(adj_high, volume_rank)
# 选出排序靠前的股票
factor[stop.notnull().any()] = np.nan # 剔除停牌的股票
factor.sort_values(ascending=lowest, inplace=True)
# 选取股票
stock_pool = factor.index[:buy_number] # 选出的股票
factor.sort_values(ascending=s_or_b, inplace=True)
stock_pool = factor.index[:buy_number]
# 选出当天应该调仓的股票
position = sdk.getPositions()
position_dict = dict([i.code, i.optPosition] for i in position)
stock_to_buy = set(stock_pool) - set(position_dict.keys())
@@ -62,7 +67,7 @@ def init_per_day(sdk):
def strategy(sdk):
step = sdk.getGlobal('step')
if step == period:
step = 0
step = 1
today = sdk.getNowDate()
sdk.sdklog(today,'====================')
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

+145
View File
@@ -0,0 +1,145 @@
# -*- coding:utf-8 -*-
from CloudQuant import MiniSimulator
import numpy as np
import pandas as pd
username = 'Harvey_Sun'
password = 'P948894dgmcsy'
Strategy_Name = 'WQ_alpha#083_10_100'
INIT_CAP = 100000000
START_DATE = '20130101'
END_DATE = '20161231'
Fee_Rate = 0.001
program_path = 'C:/cStrategy/'
buy_number = 100
period = 10
s_or_b = False # true表示选因子较小的股票,false表示选因子较大的股票
def correlation(x, y):
upside = ((x - x.mean()) * (y - y.mean())).sum(skipna=False)
dnside = x.std() * y.std()
result = upside / dnside
return result
def initial(sdk):
sdk.prepareData(['LZ_GPA_QUOTE_THIGH', 'LZ_GPA_QUOTE_TVOLUME',
'LZ_GPA_QUOTE_TLOW', 'LZ_GPA_QUOTE_TCLOSE', 'LZ_GPA_QUOTE_TVALUE',
'LZ_GPA_CMFTR_CUM_FACTOR', 'LZ_GPA_SLCIND_STOP_FLAG'])
stock_pool = []
sdk.setGlobal('stock_pool', stock_pool)
step = period
sdk.setGlobal('step', step)
def init_per_day(sdk):
step = sdk.getGlobal('step')
if step == period:
stock_list = sdk.getStockList()
high = pd.DataFrame(sdk.getFieldData('LZ_GPA_QUOTE_THIGH')[-7:], columns=stock_list)
low = pd.DataFrame(sdk.getFieldData('LZ_GPA_QUOTE_TLOW')[-7:], columns=stock_list)
close = pd.DataFrame(sdk.getFieldData('LZ_GPA_QUOTE_TCLOSE')[-7:], columns=stock_list)
volume = pd.DataFrame(sdk.getFieldData('LZ_GPA_QUOTE_TVOLUME')[-7:], columns=stock_list)
value = pd.DataFrame(sdk.getFieldData('LZ_GPA_QUOTE_TVALUE')[-7:], columns=stock_list)
adj_f = pd.DataFrame(sdk.getFieldData('LZ_GPA_CMFTR_CUM_FACTOR')[-7:], columns=stock_list)
stop = pd.DataFrame(sdk.getFieldData('LZ_GPA_SLCIND_STOP_FLAG')[-8:], columns=stock_list)
volume.replace(0, np.nan, inplace=True)
adj_high = high * adj_f
adj_low = low * adj_f
adj_close = close * adj_f
adj_volume = volume / adj_f
# 计算昨天的factor
temp = (adj_high - adj_low) / adj_close.rolling(window=5).mean()
volume_rank = adj_volume.rank(axis=1, pct=True)
vwap = value / adj_volume
upside = temp.diff(2).rank(axis=1, pct=True).iloc[-1] * volume_rank.iloc[-1]
dnside = (temp / (vwap - adj_close)).iloc[-1]
factor = upside / dnside
factor[adj_close.isnull().any()] = np.nan
# 选出排序靠前的股票
factor[stop.notnull().any()] = np.nan # 剔除停牌的股票
factor.sort_values(ascending=s_or_b, inplace=True)
stock_pool = factor.index[:buy_number]
# 选出当天应该调仓的股票
position = sdk.getPositions()
position_dict = dict([i.code, i.optPosition] for i in position)
stock_to_buy = set(stock_pool) - set(position_dict.keys())
stock_to_sell = set(position_dict.keys()) - set(stock_pool)
sdk.setGlobal('position_dict', position_dict)
sdk.setGlobal('stock_to_buy', stock_to_buy)
sdk.setGlobal('stock_to_sell', stock_to_sell)
else:
pass
def strategy(sdk):
step = sdk.getGlobal('step')
if step == period:
step = 1
today = sdk.getNowDate()
sdk.sdklog(today, '====================')
position_dict = sdk.getGlobal('position_dict')
stock_to_buy = sdk.getGlobal('stock_to_buy')
stock_to_sell = sdk.getGlobal('stock_to_sell')
quotes = sdk.getQuotes(list(stock_to_buy | stock_to_sell))
sell_orders = []
for stock in stock_to_sell:
if stock in quotes.keys():
price = quotes[stock].open
volume = position_dict[stock]
order = [stock, price, volume, -1]
sell_orders.append(order)
if sell_orders:
sdk.makeOrders(sell_orders)
sdk.sdklog('===sell orders===')
sdk.sdklog(np.array(sell_orders))
available_cash = sdk.getAccountInfo().availableCash
available_cash_one_stock = available_cash / len(stock_to_buy)
buy_orders = []
for stock in stock_to_buy:
if stock in quotes.keys():
price = quotes[stock].open
volume = int(available_cash_one_stock / (price * 100)) * 100
if volume > 0:
order = [stock, price, volume, 1]
buy_orders.append(order)
if buy_orders:
sdk.makeOrders(buy_orders)
sdk.sdklog('===buy orders===')
sdk.sdklog(np.array(buy_orders))
else:
step += 1
sdk.setGlobal('step', step)
config = {
'username': username,
'password': password,
'initCapital': INIT_CAP,
'startDate': START_DATE,
'endDate': END_DATE,
'strategy': strategy,
'initial': initial,
'preparePerDay': init_per_day,
'feeRate': Fee_Rate,
'strategyName': Strategy_Name,
'logfile': '%s.log' % Strategy_Name,
'rootpath': program_path,
'executeMode': 'D',
'feeLimit': 5,
'cycle': 10,
'dealByVolume': True,
'allowForTodayFactors': ['LZ_GPA_SLCIND_STOP_FLAG']
}
if __name__ == "__main__":
# 在线运行所需代码
import os
config['strategyID'] = os.path.splitext(os.path.split(__file__)[1])[0]
MiniSimulator(**config).run()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

+2 -1
View File
@@ -1,2 +1,3 @@
*.csv
*.log
*.log
*.png
Binary file not shown.
+5 -5
View File
@@ -110,7 +110,6 @@ def factor_cal(data, factor_id, no_zdt=False, no_st=False, no_new=False, save=Fa
volume[rolling_null(close, 63)] = np.nan
cap[rolling_null(close, 63)] = np.nan
adj_OPEN = OPEN * price_adj_f
adj_close = close * price_adj_f
adj_high = high * price_adj_f
@@ -119,7 +118,6 @@ def factor_cal(data, factor_id, no_zdt=False, no_st=False, no_new=False, save=Fa
returns = adj_close.pct_change()
vwap = value / adj_volume
print '开始计算'
if factor_id == '001':
returns[returns < 0] = returns.rolling(window=20).std(skipna=False)
@@ -232,7 +230,7 @@ def factor_cal(data, factor_id, no_zdt=False, no_st=False, no_new=False, save=Fa
factor[rolling_null(close, 10)] = np.nan
factor[rolling_stop(stop, 10)] = np.nan
elif factor_id == '019':
factor = -1 * np.sign(adj_close.diff(7)) * (1 + returns.rolling(window=250).sum())
factor = -1 * np.sign(adj_close.diff(7)) * ((1 + returns.rolling(window=250).sum()).rank(axis=1, pct=True) + 1)
factor[rolling_null(close, 250)] = np.nan
factor[rolling_stop(stop, 8)] = np.nan
elif factor_id == '020':
@@ -1139,7 +1137,9 @@ data = {'high': high,
'price_adj_f': price_adj_f}
factor = factor_cal(data, '004', no_zdt=False, no_st=False, no_new=False)
factor = factor_cal(data, '019', no_zdt=False, no_st=False, no_new=True, save=True)
save_factor(factor, '015', no_zdt=True)
factor_006 = factor_cal(data, '006', no_zdt=False)
factors = pd.concat([factor.stack(), factor_006.stack()], axis=1)
days = factors.index.levels[0]
@@ -1179,7 +1179,7 @@ a['group_mean'].mean().plot()
a['group_mean']['Factor Average'].plot(figsize=(14, 7))
a['group_return'].columns.name
a = _analysis(stt, data, 'close-close', stock_number=50, ascending=True, period=10)
a = _analysis(stt, data, 'close-close', stock_number=10, ascending=False, period=10)
a['mean_return'].mean()
a['factor_mean'].min()
(a['mean_return'] + 1).cumprod().plot(figsize=(14, 7))