def caculate_max_drawdown(data, window=252):
"""
计算最大回撤比
:param data:
:param window: int, 时间窗口设置,默认为252(日k)
:return:
"""
data['close'] = 10000 * (1 + data['cum_profit'])
data['roll_max'] = data['close'].rolling(window=window, min_periods=1).max()
data['daily_dd'] = data['close'] / data['roll_max'] - 1
data['max_dd'] = data['daily_dd'].rolling(window, min_periods=1).min()
return data
def compose_signal(data):
"""
整合信号
:param data:
:return:
"""
data['buy_signal'] = np.where((data['buy_signal'] == 1)
& (data['buy_signal'].shift(1) == 1), 0, data['buy_signal'])
data['sell_signal'] = np.where((data['sell_signal'] == -1)
& (data['sell_signal'].shift(1) == -1), 0, data['sell_signal'])
data['signal'] = data['buy_signal'] + data['sell_signal']
return data
def calculate_prof_pct(data):
"""
计算单次收益率:开仓、平仓(开仓的全部股数)
:param data:
:return:
"""
data.loc[data['signal'] != 0, 'profit_pct'] = data['close'].pct_change()
data = data[data['signal'] == -1]
return data
def week_period_strategy(code, time_freq, start_date, end_date):
"""
周期选股(周四买,周一卖)
:param code:
:param time_freq:
:param start_date:
:param end_date:
:return:
"""
data = st.get_single_price(code, time_freq, start_date, end_date)
data['weekday'] = data.index.weekday
data['buy_signal'] = np.where((data['weekday'] == 3), 1, 0)
data['sell_signal'] = np.where((data['weekday'] == 0), -1, 0)
data = base.compose_signal(data)
data = base.calculate_prof_pct(data)
return data
if __name__ == '__main__':
df = week_period_strategy('000001.XSHE', 'daily', None, datetime.date.today())
print(df[['close', 'signal', 'profit_pct']])
print(df[['close', 'signal', 'profit_pct']].describe())