# 机器学习之matlab算法SVM用150天数据预测上证指数的涨跌

### Matlab基于SVM的上证指数涨跌预测

#数据的提取

clear all
clc

t_train = datatest5(:,1);% 表示访问该矩阵的所有行的第一列；
p_train = datatest5; % 表示建立一个等效矩阵；
% [m,n] = size(y);  获取矩阵各维的长度
% kp = y(2:m,3); 表示访问sh矩阵2到m行的第一列
% kpx = y(2:m-1,:);  表示访问sh矩阵1到m-1行的所有列

[pn_train,inputps] = mapminmax(p_train');
pn_train = pn_train';
[tn_train,outputps] = mapminmax(t_train');
tn_train = tn_train';

%% 选择回归预测分析最佳的SVM参数c&g
[c,g] = meshgrid(-10:0.5:10,-10:0.5:10);
[m,n] = size(c);
cg = zeros(m,n);
eps = 10^(-4);
v = 5;
bestc = 0;
bestg = 0;
mis = Inf;
for i = 1:m
for j = 1:n
cmd = ['-v ',num2str(v),' -t 2',' -c ',num2str(2^c(i,j)),' -g ',num2str(2^g(i,j) ),' -s 3 -p 0.1'];
cg(i,j) = libsvmtrain(tn_train,pn_train,cmd);
if cg(i,j) < mis
mis = cg(i,j);
bestc = 2^c(i,j);
bestg = 2^g(i,j);
end
if abs(cg(i,j) - mis) <= eps && bestc > 2^c(i,j)
mis = cg(i,j);
bestc = 2^c(i,j);
bestg = 2^g(i,j);
end
end
end
% 2. 创建/训练SVM
cmd = [' -t 2',' -c ',num2str(bestc),' -g ',num2str(bestg),' -s 3 -p 0.01'];
model = libsvmtrain(tn_train,pn_train,cmd);
[Predict_1,error_1,decision_values1] = libsvmpredict(tn_train,pn_train,model);

predict_1 = mapminmax('reverse',Predict_1,outputps);
result_1 = [t_train predict_1];

%% VI. 绘图
figure(1)
plot(1:length(t_train),t_train,'r-*',1:length(t_train),predict_1,'b:o')
axis([0 160,-inf,inf])
grid on
legend('真实值','预测值')
xlabel('日期')
ylabel('开盘指数')
string_1 = {'预测结果对比';
['mse = ' num2str(error_1(2)) ' R^2 = ' num2str(error_1(3))]};
title(string_1)
figure(2);
mis = predict_1 - t_train;
plot(mis,'rd');
title('误差图(predicted data - original data)','FontSize',12);
xlabel('日期','FontSize',12);
ylabel('误差量','FontSize',12);
grid on;

figure(3);
mis_1 = (predict_1 - t_train)/t_train;
plot(mis_1,'rd');
title('相对误差图(predicted data - original data)/original data','FontSize',12);
xlabel('日期','FontSize',12);
ylabel('相对误差量','FontSize',12);
grid on;



05-27 5850
03-10 176
10-07 2万+
05-05 11万+
01-27 3万+
06-13 4万+