Monday, March 1, 2010

How to generate a Candlestick chart in FreeMAT or MATLAB

The plot below is generated in FreeMAT, it can also be run at MATLAB:








function gen_chart(D,O,H,L,C,symbol)
    %
    % This function generates a candlestick chart for a given O,H,L,C data
    % D is dates
    % O is open
    % H is high
    % L is low
    % C is close
    % symbol
    %
    % Example:
    % [D O H L C V]=get_symbol_data('F',150);
    % gen_chart(D,O,H,L,C,'F');
    %
    %
    %   Copyright 2010 EdgeMe
    %   $Revision: 1.0.0.0 $
    %   EdgeMe, 28-Feb-2010
    %
    %
    if nargin<6
        error('Not enough inputs');
    end



    datapoints=length(D);
    %make sure we have the same length of data
    if length(O) ~=datapoints || length(H) ~=datapoints || length(L) ~=datapoints ||length(C) ~=datapoints
        error('Data must be in the same length');
    end


    figure;


    hold on;
    %draw low to high lines
    for i=1:datapoints
        plot([i i],[L(i) H(i)],'Color','k');
        if C(i)>O(i)
            plot([i i],[O(i) C(i)],'linewidth',3,'color','g');
        else
            plot([i i],[O(i) C(i)],'linewidth',3,'color','r');
        end
    end


    title(symbol);
    hold off;
    grid on;

    %
    xlim([1 datapoints+1]);
    y=get(gca,'ylim');
    ymin=int16(y(1)-0.5);
    ymax=int16(y(2)+0.5);
    ylim([ymin ymax]);


    XTick=[];
    j=1;
    for i=1:10:datapoints
        XTick(j)=i;
        j=j+1;
    end

    %Set XTicklabel to an empty string
    set(gca,'XTick',XTick,'XTickLabel','')

    for i=1:length(XTick)
        % Set the new xTickLabels of Dates
        hText = text(XTick(i), double(ymin), D{XTick(i)});
        set(hText,'Rotation',28,'HorizontalAlignment','right');
    end

end

Sunday, February 28, 2010

Scripts updates

Per readers comments, the following two scripts have been updated:

get_symbol_data.m
adx2.m

Thursday, February 18, 2010

Option Pricing Black-Scholes script for MATLAB and FreeMAT


function [C, P]= option_bs(S,X,r,sigma,days)
    %
    %  This function to calculate Call and Put price per Black-Scholes formula.
    %  This function can be run both at FreeMAT and MATLAB,
    %  This function should be same as MATLAB's financial toolbox function
    %  blsprice.
    %
    % C: call price
    % P: put price
    % S: stock price at time 0
    % X:  strike price
    % r: risk-free interest rate
    % sigma: volatility of the stock price measured as annual standard deviation
    % days: numbers of days remaining in the option contract, this will be converted into unit of years.
    % Black-Scholes formula:
    %  C = S N(d1) - Xe-rt N(d2)
    %  P = Xe-rt N(-d2) - S N(-d1)
    %

    T=days/365;

    % for call
    d1 = (log(S/X) + (r + 0.5*sigma^2)*T)/(sigma*sqrt(T));
    d2 = d1 - sigma*sqrt(T);
    N1 = 0.5*(1+erf(d1/sqrt(2)));
    N2 = 0.5*(1+erf(d2/sqrt(2)));

    C = S*N1-X*exp(-r*T)*N2;

    % for put

    N1 = 0.5*(1+erf(-d1/sqrt(2)));
    N2 = 0.5*(1+erf(-d2/sqrt(2)));

    P = X*exp(-r*T)*N2 - S*N1;
end

Tuesday, February 16, 2010

get_hisVolatility.m


function vol = get_hisVolatility(closes, N)
%
%   This script is to calculate the historical
%   volatility for close prices using N days sliding window
%   If N is not specified, a default of 20 days will be
%   used.
%
%   Copyright 2010 EdgeMe
%   EdgeMe, 12-Feb-2010
%
%
if nargin==0
    N=20;
end

    dataN=numel(closes);
    vol=[];
    if dataN<N
      warning ('Not enough data')
      return;
    end

    log_change(1)=0;
    for i=2:dataN
    log_change(i) = log(closes(i)/closes(i-1));
    end

    for i=N+1:dataN
    stdev = std(log_change(i-N+1:i));

    % Normalize to annual volatility
    vol(i)= stdev*sqrt(252);
    end

    %fillin the first N days using N+1 vol
    for i=1:N
        vol(i)=vol(N+1);
    end

end

Monday, February 15, 2010

ema.m


function dataout = ema(datain,period)
%
% This function is to get EMA of a given datain and a given period
%
%   Copyright 2010 EdgeMe
%   EdgeMe, 10-Feb-2010
%
%
    f = 2/(period+1);
    N = numel(datain);
    dataout = zeros(N,1);
    dataout(1) = datain(1);
    for i=2:N
    dataout(i) = f*(datain(i)-dataout(i-1)) + dataout(i-1);
    end

end

How to generate a list of stocks according to your own magic formula – A reader made it working

How to generate a list of stocks according to your own magic formula – Part One

How to generate a list of stocks according to your own magic formula – Part Two


After I posted the above article, a reader sent me an email pointed out it requires one more script "split_str_by_comma.m".

After sending him the script and I also updated the script "get_symbols.m". Today he sent an email saying that

"It is working great now. thank you so much..."


Thanks for visiting my blog, and I hope my blog will help others too. 

Sunday, February 14, 2010

split_str_by_comma.m


function ret_cell_array=split_str_by_comma(str)
%
% This function is to split a str by comma, return as cell array
%
% EXAMPLE:
% ret_cell_array=split_str_by_comma('12, 34, 56');
% the ret_cell_array should be {'12','34','56'}
%
% If you have MATLAB, you can use ret_cell_array=regexp(str,',','split') to get job done;
%
%   Copyright 2010 EdgeMe
%   EdgeMe, 10-Feb-2010
%
%

    %find out where are the commas
    commas=regexp(str,',');

    %if no comma, just return the str
    if isempty(commas)
        ret_cell_array={str};
        return;
    else %we found comma(s)

        %first comma, also get rid of space
        ret_cell_array{1}=strrep(str(1:commas(1)-1),' ','');

        for i=1:numel(commas)-1

            ret_cell_array{end+1}=strrep(str(commas(i)+1:commas(i+1)-1),' ','');

        end

        %last one
        if length(str)>commas(end)
            ret_cell_array{end+1}=strrep(str(commas(end)+1:length(str)),' ','');
        end


    end


 end