Showing posts with label Visualization Script. Show all posts
Showing posts with label Visualization Script. Show all posts

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