写论文第四天:选择最佳的参数

1.nan函数

>> nan(1)


ans =


   NaN


>> nan(1,1)


ans =


   NaN


>> nan(1,2)


ans =


   NaN   NaN


>> nan(2,1)


ans =


   NaN
   NaN


>> nan(2,2)


ans =


   NaN   NaN
   NaN   NaN



2.tic toc

tic和toc用来记录matlab命令执行的时间。
   tic用来保存当前时间,而后使用toc来记录程序完成时间。
   两者往往结合使用,用法如下:
   tic
   operations
   toc
   显示时间单位:秒


3.[~]

[~,m]=size(coord)中size得到coord的行列数赋值给[~,m],~表示占位,是2009以后的版本才用的!就是只要列m的值!


4.从网上下载的matlab工具箱软件包,要怎么加载进软件中?

1.将下载下的软件包解压,放在MATLAB下的toolbox中。
2.点击MATLAB窗口中的file→set path...→在弹出的对话框中找到解压之后的工具包→点击-add with subfolders。此时工具包加入了MATLAB搜索路径中,可以直接使用。之后点击save保存设置,退出


5.leadlag

function varargout = leadlag(P,N,M,scaling,cost)
%LEADLAG returns a trading signal for a simple lead/lag ema indicator
%   LEADLAG returns a trading signal for a simple lead/lag exponential
%   moving-average technical indicator.
%
%   S = LEADLAG(PRICE) returns a trading signal based upon a 12-period
%   lead and a 26-period lag.  This is the default value used in a MACD
%   indicator.  S is the trading signal of values -1, 0, 1 where -1 denotes
%   a sell (short), 0 is neutral, and 1 is buy (long).
%
%   S = LEADLAG(PRICE,N,M) returns a trading signal for a N-period lead and
%   a M-period lag.
%
%   [S,R,SH,LEAD,LAG] = LEADLAG(...) returns the trading signal S, the
%   absolute return in R, the Sharpe Ratio in SH calcualted using R, and
%   the LEAD or LAG series.
%
%   EXAMPLE:
%   % IBM
%     load ibm.dat
%     [s,~,~,lead,lag] = leadlag(ibm(:,4));
%     ax(1) = subplot(2,1,1);
%     plot([ibm(:,4),lead,lag]);
%     title('IBM Price Series')
%     legend('Close','Lead','Lag','Location','Best')
%     ax(2) = subplot(2,1,2);
%     plot(s)
%     title('Trading Signal')
%     set(gca,'YLim',[-1.2 1.2])
%     linkaxes(ax,'x')
%
%   % Disney
%     load disney
%     dis_CLOSE(isnan(dis_CLOSE)) = [];
%     [s,~,~,lead,lag] = leadlag(dis_CLOSE);
%     ax(1) = subplot(2,1,1);
%     plot([dis_CLOSE,lead,lag]);
%     title('Disney Price Series')
%     legend('Close','Lead','Lag','Location','Best')
%     ax(2) = subplot(2,1,2);
%     plot(s)
%     title('Trading Signal')
%     set(gca,'YLim',[-1.2 1.2])
%     linkaxes(ax,'x')
%
%   See also movavg, sharpe, macd

%%
% Copyright 2010, The MathWorks, Inc.
% All rights reserved.

%% Process input args
if ~exist('scaling','var')
    scaling = 1;
end

if ~exist('cost','var')
    cost = 0;
end

if nargin < 2
    % defualt values
    M = 26;
    N = 12;
elseif nargin < 3
    error('LEADLAG:NoLagWindowDefined',...
        'When defining a leading window, the lag must be defined too')
end %if

%% Simple lead/lag ema calculation
if nargin > 0
    s = zeros(size(P));
    [lead,lag] = movavg(P,N,M,'e');
    s(lead>lag) = 1;
    s(lag>lead) = -1;
    r  = [0; s(1:end-1).*diff(P)-abs(diff(s))*cost/2];
    sh = scaling*sharpe(r,0);
    
    if nargout == 0 % Plot
        %% Plot results
        ax(1) = subplot(2,1,1);
        plot([P,lead,lag]); grid on
        legend('Close',['Lead ',num2str(N)],['Lag ',num2str(M)],'Location','Best')
        title(['Lead/Lag EMA Results, Annual Sharpe Ratio = ',num2str(sh,3)])
        ax(2) = subplot(2,1,2);
        plot([s,cumsum(r)]); grid on
        legend('Position','Cumulative Return','Location','Best')
        title(['Final Return = ',num2str(sum(r),3),' (',num2str(sum(r)/P(1)*100,3),'%)'])
        linkaxes(ax,'x')
    else
        for i = 1:nargout
            switch i
                case 1
                    varargout{1} = s;
                case 2
                    
                    varargout{2} = r;
                case 3
                    varargout{3} =  sh;
                case 4
                    varargout{4} = lead;
                case 5
                    varargout{5} = lag;
                otherwise
                    warning('LEADLAG:OutputArg',...
                        'Too many output arguments requested, ignoring last ones');
            end %switch
        end %for
    end %if
else
    %% Run Example
    example(1:2)
end %if

%% Examples
function example(ex)
for e = 1:length(ex)
    for e = 1:length(ex)
        switch ex(e)
            case 1
                figure(1), clf
                load ibm.dat
                [s,~,~,lead,lag] = leadlag(ibm(:,4));
                ax(1) = subplot(2,1,1);
                plot([ibm(:,4),lead,lag]);
                title('IBM Price Series')
                legend('Close','Lead','Lag','Location','Best')
                ax(2) = subplot(2,1,2);
                plot(s)
                title('Trading Signal')
                set(gca,'YLim',[-1.2 1.2])
                linkaxes(ax,'x')
            case 2
                figure(2),clf
                load disney
                dis_CLOSE(isnan(dis_CLOSE)) = [];
                [s,~,~,lead,lag] = leadlag(dis_CLOSE);
                ax(1) = subplot(2,1,1);
                plot([dis_CLOSE,lead,lag]);
                title('Disney Price Series')
                legend('Close','Lead','Lag','Location','Best')
                ax(2) = subplot(2,1,2);
                plot(s)
                title('Trading Signal')
                set(gca,'YLim',[-1.2 1.2])
                linkaxes(ax,'x')
        end %switch
    end %for
end %for
>> type rat

function [N,D] = rat(X,tol)
%RAT    Rational approximation.
%   [N,D] = RAT(X,tol) returns two integer matrices so that N./D
%   is close to X in the sense that abs(N./D - X) <= tol*abs(X).
%   The rational approximations are generated by truncating continued
%   fraction expansions.   tol = 1.e-6*norm(X(:),1) is the default.
%
%   S = RAT(X) or RAT(X,tol) returns the continued fraction 
%   representation as a string.
%
%   The same algorithm, with the default tol, is used internally
%   by MATLAB for FORMAT RAT.
%
%   Class support for input X:
%      float: double, single
%
%   See also FORMAT, RATS.

%   Copyright 1984-2006 The MathWorks, Inc. 
%   $Revision: 5.18.4.5 $  $Date: 2006/10/02 16:33:02 $

% Approximate x by
%
%                              1
%         d1 + ----------------------------------
%                                 1
%              d2 + -----------------------------
%                                   1
%                   d3 + ------------------------
%                                      1
%                        d4 + -------------------
%                                        1
%                             d5 + --------------
%                                           1
%                                  d6 + ---------
%                                             1
%                                       d7 + ----
%                                             d8
%
% The d's are obtained by repeatedly picking off the integer part and 
% then taking the reciprocal of the fractional part.  The accuracy of
% the approximation increases exponentially with the number of terms
% and is worst when x = sqrt(2).  For x = sqrt(2), the error with k
% terms is about 2.68*(.173)^k, which is
%
%         1    4.6364e-01
%         2    8.0210e-02
%         3    1.3876e-02
%         4    2.4006e-03
%         5    4.1530e-04
%         6    7.1847e-05
%         7    1.2430e-05
%         8    2.1503e-06
%         9    3.7201e-07
%        10    6.4357e-08

if nargin < 2
    tol = 1.e-6*norm(X(isfinite(X)),1);
end
if ~isreal(X)
    if norm(imag(X),1) <= tol*norm(real(X),1)
        X = real(X);
    elseif nargout > 1
        [NR,DR] = rat(real(X));
        [NI,DI] = rat(imag(X));
        D = lcm(DR,DI);
        N = D./DR.*NR + D./DI.*NI*i;
        return
    else
        N = strvcat(rat(real(X)),' +i* ...',rat(imag(X)));
        return
    end
end
if nargout > 1
    N = zeros(size(X), class(X));
    D = zeros(size(X), class(X));
else
    N = zeros(0,0,class(X)); 
end
for j = 1:numel(X)
    x = X(j);
    if ~isfinite(x), % Special case for inf, -inf, NaN
        if nargout <=1
            s = int2str(x);
            k = length(s)-size(N,2);
            N = char([N ' '*ones(j-1,k); s ' '*ones(1,-k)]);
        else
            if ~isnan(x), N(j) = sign(x); else N(j) = 0; end
            D(j) = 0;
        end
    else
        k = 0;
        C = [1 0; 0 1];    % [n(k) n(k-1); d(k) d(k-1)];
        while 1
            k = k + 1;
            neg = x < 0;
            d = round(x);
            if ~isinf(x),
                x = x - d;
                C = [C*[d;1] C(:,1)];
            else % Special case for +/- inf
                C = [[x;0] C(:,1)];
            end
            if nargout <= 1
                d = int2str(abs(d));
                if neg, d = ['-' d]; end
                if k == 1
                    s = d;
                elseif k == 2
                    s = [s ' + 1/(' d ')'];
                else
                    p = find(s==')',1);
                    s = [s(1:p-1) ' + 1/(' d ')' s(p:p+k-3)];
                end
            end
            if (x==0) || (abs(C(1,1)/C(2,1) - X(j)) <= max(tol,eps(X(j))))
               break
            end
            x = 1/x;
        end
        if nargout > 1
            N(j) = C(1,1)/sign(C(2,1));
            D(j) = abs(C(2,1));
        else
            k = length(s)-size(N,2);
            N = char([N ' '*ones(j-1,k); s ' '*ones(1,-k)]);
        end
    end
end

6.surf surfc

参考:http://www-rohan.sdsu.edu/doc/matlab/techdoc/ref/surfc.html

参考:http://zhidao.baidu.com/link?url=QjC3DLF_thfgEEQ0wy908y34aopgmLDUqrc75Mo7tIQ2yPtaV2VMhORfaaVVf_Mbaerwi3RtUZPg0AVTk0GNzK


7.view函数

MATLAB提供了设置视点的函数view。


其调用格式为: view(az,el)


az是azimuth(方位角)的缩写,EL是elevation(仰角)的缩写。它们均以度为单位。系统缺省的视点定义为方位角-37.5°,仰角30°。


当x轴平行观察者身体,y轴垂直于观察者身体时,az=0; 以此点为起点,绕着z轴顺时针运动,az为正,逆时针为负。


EL 为观察者眼睛与xy平面形成的角度。
当观察者的眼睛在xy平面上时,el=0; 向上el为正,向下为负;


下面是一些例子:
AZ = -37.5, EL = 30 是默认的三维视角.
AZ = 0, EL = 90 是2维视角,从图形正上方向下看,显示的是xy平面.
AZ = EL = 0 看到的是xz平面.
AZ = 180,EL=0 是从背面看到的xz平面.
VIEW(2) 设置默认的二维视角, AZ = 0, EL = 90.
VIEW(3) 设置默认的三维视角, AZ = -37.5, EL = 30.


VIEW([X Y Z]) 设置Cartesian坐标系的视角,[X Y Z]向量的长度大小被忽略.
[AZ,EL] = VIEW 返回当前的方位角和仰角.


8.matlab语句[x1,row]=max(x);是什么意思
请问,如下matlab语句什么意思啊,我小白
[x1,row]=max(x);
row=max(row);
[maxV,column]=max(x1);


第一句是按列来求矩阵的最大值,x1是x的每列的最大值,row是每列最大值所在的行数
第二句是第一句所求row的最大值
第三句是跟第一句意思一样
>> a=[1,2,3,4;1,4,2,6]
a =
1 2 3 4
1 4 2 6
>> [x1,y1]=max(a)
x1 =
1 4 3 6
y1 =
1 2 1 2
>> y1=max(y1)
y1 =
2
>> [maxV,column]=max(x1)
maxV =
6
column =
4


8.

clc, clear all, close all      
load CSI300.mat      
CSI300_1Mn=raw_CSI300_1Mn(:,4);      
CSI300_1Mn=CSI300_1Mn(1:end);      
CSI300_EOD=raw_CSI300_EOD(:,4);      
testPts=floor(0.8*length(CSI300_EOD));      
CSIClose=CSI300_EOD(1:testPts);      
CSICloseV=CSI300_EOD(testPts+1:end);     
%计算Sharpe指数  
[lead,lag]=movavg(CSIClose,20,30,'e');      
%假设全年有250个交易日    
s=zeros(size(CSIClose));    
s(lead>lag)=1;%Buy    
s(lead<lag)=-1;%Sell    
r=[0;s(1:end-1).*diff(CSIClose)];%Return    
sh=sqrt(250)*sharpe(r,0);%Annual Sharpe Ratio  
%绘制初步策略的评估结果  
ax(1)=subplot(2,1,1);  
plot([CSIClose,lead,lag]),grid on  
legend('Close','Lead','Lag','Location','Best')  
title(['First Pass Results, Annual Sharpe Ratio=',num2str(sh,3)])  
ax(2)=subplot(2,1,2);  
plot([s,cumsum(r)]);grid on  
title(['Final Return = ',num2str(sum(r),3),' (',num2str(sum(r)/CSIClose(1)*100,3),'%)'])  
legend('Position','Cumulative Return','Location','Best')  
linkaxes(ax,'x')  
annualScaling=sqrt(250);  

sh=nan(100,100);
tic
for n=1:100
for m=n:100
[~,~,sh(n,m)]=leadlag(CSIClose,n,m,annualScaling);
end
end
toc
figure
surfc(sh),shading interp, lighting phong
view([80 35]),light('pos',[0.5,-0.9,0.05])
colorbar
%绘制最佳的夏普率
[maxSH,row]=max(sh);%max by column
[maxSH,col]=max(maxSH);%max by row and column
figure
leadlag(CSIClose,row(col),col,annualScaling)
disp('最佳参数组合为:')
disp(['Lead= ',num2str(row(col))]);
disp(['Lag= ',num2str(col)]);
%用于验证数据评估当前策略
figure
leadlag(CSICloseV,row(col),col,annualScaling)








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值