#### 前言

Optiver波动率预测大赛于上个月27号截止提交，比赛终于告一段落，等待着明年1月份的最终比赛结果。Kaggle上，由财大气粗的对冲基金大佬主办的金融交易类预测大赛，总能吸引大量的人气。在过去3个月的比赛中，也诞生了很多优秀的开源代码，各路神仙应用各种模型算法，在竞争激烈的榜单你追我赶。

#### 特征构建

```# 导入相关工具包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import glob

# 设置数据所在文件夹路径
data_dir = '../input/optiver-realized-volatility-prediction/'```

#### 预处理函数

```# 计算wap价格
def calc_wap(df):
return wap
def calc_wap2(df):
return wap

# 计算对数收益率
def log_return(list_stock_prices):
return np.log(list_stock_prices).diff()

# 计算已实现波动率
def realized_volatility(series):
return np.sqrt(np.sum(series**2))

# 其他函数
def count_unique(series):
return len(np.unique(series))```

Book样例数据如下：

“log_return”/”log_return2″：计算的是每个time_id内相邻两个快照的收益率，没两个快照之间的时间间隔可能不一致，如示例数据中的秒数间隔数为1、4、1、1。

```def preprocessor_book(file_path):
#calculate return etc
df['wap'] = calc_wap(df)
df['log_return'] = df.groupby('time_id')['wap'].apply(log_return)

df['wap2'] = calc_wap2(df)
df['log_return2'] = df.groupby('time_id')['wap2'].apply(log_return)

df['wap_balance'] = abs(df['wap'] - df['wap2'])

#dict for aggregate
create_feature_dict = {
'log_return':[realized_volatility],
'log_return2':[realized_volatility],
'wap_balance':[np.mean],
'volume_imbalance':[np.mean],
'total_volume':[np.mean],
'wap':[np.mean],
}
#####groupby / all seconds
df_feature = pd.DataFrame(df.groupby(['time_id']).agg(create_feature_dict)).reset_index()

df_feature.columns = ['_'.join(col) for col in df_feature.columns] #time_id is changed to time_id_

######groupby / last XX seconds
last_seconds = [300]

for second in last_seconds:
second = 600 - second

df_feature_sec = pd.DataFrame(df.query(f'seconds_in_bucket >= {second}').groupby(['time_id']).agg(create_feature_dict)).reset_index()
df_feature_sec.columns = ['_'.join(col) for col in df_feature_sec.columns] #time_id is changed to time_id_

df_feature = pd.merge(df_feature,df_feature_sec,how='left',left_on='time_id_',right_on=f'time_id__{second}')
df_feature = df_feature.drop([f'time_id__{second}'],axis=1)

#create row_id
stock_id = file_path.split('=')[1]
df_feature['row_id'] = df_feature['time_id_'].apply(lambda x:f'{stock_id}-{x}')
df_feature = df_feature.drop(['time_id_'],axis=1)

return df_feature```

```%%time
file_path = data_dir + "book_train.parquet/stock_id=0"
preprocessor_book(file_path)```

```def preprocessor_trade(file_path):
df['log_return'] = df.groupby('time_id')['price'].apply(log_return)

aggregate_dictionary = {
'log_return':[realized_volatility],
'seconds_in_bucket':[count_unique],
'size':[np.sum],
'order_count':[np.mean],
}

df_feature = df.groupby('time_id').agg(aggregate_dictionary)

df_feature = df_feature.reset_index()
df_feature.columns = ['_'.join(col) for col in df_feature.columns]

######groupby / last XX seconds
last_seconds = [300]

for second in last_seconds:
second = 600 - second

df_feature_sec = df.query(f'seconds_in_bucket >= {second}').groupby('time_id').agg(aggregate_dictionary)
df_feature_sec = df_feature_sec.reset_index()

df_feature_sec.columns = ['_'.join(col) for col in df_feature_sec.columns]

df_feature = pd.merge(df_feature,df_feature_sec,how='left',left_on='time_id_',right_on=f'time_id__{second}')
df_feature = df_feature.drop([f'time_id__{second}'],axis=1)

stock_id = file_path.split('=')[1]

return df_feature```

```file_path = data_dir + "trade_train.parquet/stock_id=0"

```def preprocessor(list_stock_ids, is_train = True):
from joblib import Parallel, delayed # parallel computing to save time
df = pd.DataFrame()

def for_joblib(stock_id):
if is_train:
file_path_book = data_dir + "book_train.parquet/stock_id=" + str(stock_id)
else:
file_path_book = data_dir + "book_test.parquet/stock_id=" + str(stock_id)

return pd.concat([df,df_tmp])

df = Parallel(n_jobs=-1, verbose=1)(
delayed(for_joblib)(stock_id) for stock_id in list_stock_ids
)
df = pd.concat(df,ignore_index = True)
return df```

#### 构建训练/测试数据集

```# 训练集
train_ids = train.stock_id.unique()
df_train = preprocessor(list_stock_ids= train_ids, is_train = True)
train['row_id'] = train['stock_id'].astype(str) + '-' + train['time_id'].astype(str)
train = train[['row_id','target']]
df_train = train.merge(df_train, on = ['row_id'], how = 'left')

# 测试集
test_ids = test.stock_id.unique()
df_test = preprocessor(list_stock_ids= test_ids, is_train = False)
df_test = test.merge(df_test, on = ['row_id'], how = 'left')```

```from sklearn.model_selection import KFold
#stock_id target encoding
df_train['stock_id'] = df_train['row_id'].apply(lambda x:x.split('-')[0])
df_test['stock_id'] = df_test['row_id'].apply(lambda x:x.split('-')[0])
stock_id_target_mean = df_train.groupby('stock_id')['target'].mean()
df_test['stock_id_target_enc'] = df_test['stock_id'].map(stock_id_target_mean) # test_set
#training
tmp = np.repeat(np.nan, df_train.shape[0])
kf = KFold(n_splits = 10, shuffle=True,random_state = 19911109)
for idx_1, idx_2 in kf.split(df_train):
target_mean = df_train.iloc[idx_1].groupby('stock_id')['target'].mean()
tmp[idx_2] = df_train['stock_id'].iloc[idx_2].map(target_mean)
df_train['stock_id_target_enc'] = tmp```

LightGBM

LightGBM模型本身是为了解决XGBoost在训练时间空间上的缺陷提出来的高效的GBDT模型，关于LightGBM模型的介绍可以参考网上丰富的资料。在这里，我们不花篇幅讲解LightGBM的原理，做一回调包侠，直接引入lightgbm模块：

```import lightgbm as lgbm
# 数据最后准备
df_train['stock_id'] = df_train['stock_id'].astype(int)
df_test['stock_id'] = df_test['stock_id'].astype(int)
X = df_train.drop(['row_id','target'],axis=1)
y = df_train['target']

# 定义目标函数
def rmspe(y_true, y_pred):
return  (np.sqrt(np.mean(np.square((y_true - y_pred) / y_true))))

def feval_RMSPE(preds, lgbm_train):
labels = lgbm_train.get_label()
return 'RMSPE', round(rmspe(y_true = labels, y_pred = preds),5), False

# 参数设置
params = {
"objective": "rmse",
"metric": "rmse",
"boosting_type": "gbdt",
'early_stopping_rounds': 30,
'learning_rate': 0.01,
'lambda_l1': 1,
'lambda_l2': 1,
'feature_fraction': 0.8,
'bagging_fraction': 0.8,
}

# 训练验证集划分
kf = KFold(n_splits=5, random_state=19901028, shuffle=True)
oof = pd.DataFrame() # out-of-fold result
models = [] # models
scores = 0.0                         # validation score
gain_importance_list = []
split_importance_list = []```

```# 模型训练
for fold, (trn_idx, val_idx) in enumerate(kf.split(X, y)):
print("Fold :", fold+1)

# create dataset
X_train, y_train = X.loc[trn_idx], y[trn_idx]
X_valid, y_valid = X.loc[val_idx], y[val_idx]

#RMSPE weight
weights = 1/np.square(y_train)
lgbm_train = lgbm.Dataset(X_train,y_train,weight = weights)
weights = 1/np.square(y_valid)
lgbm_valid = lgbm.Dataset(X_valid,y_valid,reference = lgbm_train,weight = weights)

# model
model = lgbm.train(params=params,
train_set=lgbm_train,
valid_sets=[lgbm_train, lgbm_valid],
num_boost_round=5000,
feval=feval_RMSPE,
verbose_eval=100,
categorical_feature = ['stock_id']
)

# validation
y_pred = model.predict(X_valid, num_iteration=model.best_iteration)
RMSPE = round(rmspe(y_true = y_valid, y_pred = y_pred),3)
print(f'Performance of the　prediction: , RMSPE: {RMSPE}')
#keep scores and models
scores += RMSPE / 5
models.append(model)
print("*" * 100)

# 最终的训练集的scores为0.2344```

```y_pred = df_test[['row_id']]
X_test = df_test.drop(['time_id', 'row_id'], axis = 1)

target = np.zeros(len(X_test))
#light gbm models
for model in models:
pred = model.predict(X_test[X_valid.columns], num_iteration=model.best_iteration)
target += pred / len(models)
y_pred = y_pred.assign(target = target)
y_pred.to_csv('submission.csv',index = False)```

kfold中每个fold训练一个模型，最终测试集是多个模型综合的结果（LightGBM本身就是一种集成学习）；