%% --------两股票匹配交易(一个简单的尝试)-----------
%% ------1.说明-----
%1)coded by 连长(lxbmailbox@163.com)
%2)程序设计时间:2013年12月中旬
%3)数据说明:
%原始数据为Origin.mat,第一列为交易日期(频率为日),第2列为股票stock1收盘价,
%第3列为股票stock2收盘价,第4列为两股票的价差(spread),第5列为两股票价格比(price_ratio),
%即stock1/stock2
%研究起始点为2007-09-27,终点为2013-09-27
%% ------2.提取数据-----
date=Origin(:,1);
stock1=Origin(:,2);
stock2=Origin(:,3);
spread=Origin(:,4);
price_ratio=Origin(:,5);
%% -----3.画图查看数据
%股票走势图
subplot(2,1,1);
plot(date,stock1,'r',date,stock2,'g');
datetick('x',10);
xlabel('Date');
ylabel('Close Price');
title('The Close Price of Stocks');
legend('Stock1','Srock2');
grid on;
subplot(2,1,2);
plot(date,price_ratio,'r');
datetick('x',10);
xlabel('Date');
ylabel('Price Ratio');
title('The Price Ratio of Two Stocks');
grid on;
%% ------4.参数设置及数据准备---
%参数设置
MA_length=90; %移动平均长度
Entry=2; %入场点为多少倍标准差
stop_loss_rate=0.3; %_loss和profit_taking都是规定出场点,分别为止损和止盈点
profit_taking_rate=0.1; %即价格比向均值方向移动百分之多少时,止盈;止损亦然
%计算价格比移动平均
MA=zeros(length(price_ratio),1);%初始化移动平均向量
for i=MA_length:length(price_ratio);
MA(i)=sum(price_ratio(i-MA_length+1:i))/MA_length;
MA(1:MA_length-1)=price_ratio(1:MA_length-1);
end
%计算价格比移动标准差
STD=zeros(length(price_ratio),1);%初始化标准差向量
for i=MA_length:length(price_ratio);
STD(i)=std(MA(i-MA_length+1:i));
end
%确定上下突破线(决定买入点)
upper_break=MA+Entry*STD;
lower_break=MA-Entry*STD;
% 画出移动平均及突破区间
figure;
hold on;
plot(date,price_ratio,'r');
plot(date,upper_break,'g:',date,lower_break,'g:','LineWidth',2);
datetick('x',10);
grid on;
xlabel('Date');
ylabel('Price ratio');
title('The Backtesting Result of Our Pair Trading strategy');
%% ------5.策略回测------
signalbuy=zeros(length(price_ratio),1);%初始化买入信号
signalsell=zeros(length(price_ratio),1);%初始化卖出信号
pos=zeros(length(price_ratio),1);%初始化仓位
for i=2:length(price_ratio)
%定义买入信号
if price_ratio(i-1)upper_break(i)
signalbuy(i)=1;
end
if price_ratio(i-1)>lower_break(i-1) && price_ratio(i)
signalbuy(i)=-1;
end
%定义卖出信号
if (pos(i-1)==1 && price_ratio(i)stop_loss)
signalsell(i)=1;
end
if (pos(i-1)==-1 && price_ratio(i)>profit_taking) || (pos(i-1)==-1 && price_ratio(i)
signalsell(i)=-1;
end
if pos(i-1)==0
if signalbuy(i)~=0
if signalbuy(i)==1
pos(i)=1;
plot(date(i),price_ratio(i),'ko','MarkerFaceColor','k');%进场点
profit_taking=price_ratio(i)*(1-profit_taking_rate);
stop_loss=price_ratio(i)*(1+stop_loss_rate);
else
pos(i)=-1;
plot(date(i),price_ratio(i),'ko','MarkerFaceColor','k');%进场点
profit_taking=price_ratio(i)*(1+profit_taking_rate);
stop_loss=price_ratio(i)*(1-stop_loss_rate);
end
else pos(i)=pos(i-1);
end
else
if pos(i-1)==1
if signalsell(i)==1
pos(i)=0;
plot(date(i),price_ratio(i),'mo','MarkerFaceColor','m');%出场点
else pos(i)=pos(i-1);
end
else
if signalsell(i)==-1
pos(i)=0;
plot(date(i),price_ratio(i),'mo','MarkerFaceColor','m');%出场点
else pos(i)=pos(i-1);
end
end
end
end
%% 回测结果