Matlab in Finance

Discussion in 'Trading Software' started by nitro, Sep 29, 2004.

  1. prophet

    prophet

    It's even simpler if you use a high level language like Matlab. You could start with a single data structure you load from a csv file like:

    data=load('year_of_bar_data.csv')

    ...where the columns in the csv file could be:
    date, time, open, high, low, close, volume plus any other information, such as OHLC for other markets. Each row in the CSV is a bar. The array 'data' is referenced exactly as you would reference the CSV file if you loaded it into a spreadsheet. The first index is bar #. The second is field index. Thus the closing price for bar # 12345 is data(12345,6 ); The entire vector of closing prices is data:),6 ). The entire "structure" for bar # 12345 is data(12345,: ). There is no need to define structures or classes, allocate arrays. Matlab handles the details. By the way I put some spaces after the : since ET converts :) to smiley faces.

    Example calculations:

    In-place calculations:
    bar_range=data:),4)-data:),5); % high - low
    relative_close=(data:),6)-data:),5))./bar_range; % relative position of closing price in each bar

    First differences:
    change_magnitude=[0; abs(diff(data:),6),1,1))]; %absolute value of close->close price changes (volatility).

    SMA (method 1):
    n=10;
    cm=cumsum(data:),6),1);
    price_ma=(cm-cm(max(1,(1:end)-n)))/n; % n=10 period SMA of price. First n bars will be in error versus other methods.

    SMA (method 2):
    n=10;
    price_ma=conv2(data:),6),[zeros(n,1); ones(n,1)/n],'same'); % this uses a convolution and is slower, but can do arbitrary shaped moving averages.

    All of these operations can span across multiple dimensions. 'data' need not be restricted to two dimensions. Thus you could process 1000 markets of OHLC bar data simultaniously with these same lines of code with a few minor changes.

    putting it together:
    n=100;
    ma_filter=(n:-1:1)';
    ma_filter=[zeros(n,1); ma_filter/sum(ma_filter)];
    money_flow=conv2(data:),6).*data:),7).*[0; sign(diff(data:),6),1,1))],ma_filter,'same');

    This is a 100 period ramp-weighted MA of money traded (price*volume) per bar using a positive sign for green bars, negative for red bars. This is the classical "money flow" indicator. Units are in whatever currency the price data is in.

    Plot these against price:

    subplot(2,1,1);
    plot(data:),6)); %plot closing prices;
    subplot(2,1,2);
    plot(money_flow); %plot money flow

    Or you could overlay them, or use the money flow to color bars red or green.

    As you can see, very little code is needed to do things in Matlab, assuming you take advantage of vector/matrix notation. Otherwise the code will be similar to C, and you'll need "for" loops and incur overhead. The final trading may require a "for" loop or MEX function. However, the indicator prototyping, calculating and exploration can usually all be vectorized. What can't be vectorized can be done by a MEX function coded in C. I do most indicator synthesis in ordinary matlab code and the final simulation of trades in a MEX function.
     
    #62     Nov 7, 2004
  2. nitro

    nitro

    #63     Nov 7, 2004
  3. HLB

    HLB

    Hi prophet,

    I don't like using indices, it make code less readable.
    I want code to look like EasyLangauge.
    I have to possible solutions:

    1. Define constants for column indices, i.e:
    LOW =5
    CLOSE = 6

    and then use: data(bar, CLOSE)

    OR

    2. Use structs, i.e.

    data(bar).close > data(bar).open

    While #2 is more readable, I think #1 is btter for performance reasons, or maybe both are not good?

    TIA
     
    #64     Nov 7, 2004
  4. prophet

    prophet

    Hi HLB,

    Yes I should have used labels or constants in those examples.

    Structs are also helpful for organization, though I find it easier to write data:),3:5) or data:),open:close) if I want the OHLC fields as a 2D array instead of having to construct [data.open data.high data.low data.close] if I was using a structure. Otherwise the structure is cleaner. I use structures quite a bit, mostly for all the small arrays and scalars variables, less often for the large arrays.

    One issue with a structure is do you use an array of structures or a structure containing arrays? data(bar).open or data.open(bar)? A structure of arrays should be faster. However this is just a 2 dimensional example. Whenever I get into high-dimensional analysis the simplicity of arrays keeps the headaches at bay.
     
    #65     Nov 7, 2004
  5. #66     Nov 8, 2004
  6. monarc

    monarc

    Jmedved:
    Cannot comment on the Metlab side of things, but we really tried to make our API very simple. If you find an experienced programmer to deal with it and they need some assistance, please have them contact us.
    *************************************************

    Hello,

    I am an University of Chicago MBA student and I have been following this thread since I deal with MATLAB at work,albeit as a
    an electronics engineer(control Systems)....I have used various toolboxes in Matlab, Even Used Auto code Generation to quickly prototype the logic neccessary. The code seemed to robust and worked pretty well for the project.

    BTW, I was in the MATLAB for finance seminar that was held in Chicago...

    I am trying to make a career change into finance, especially Sales & Trading or investment Management. I have recently looked at the Datafeed Toolbox in the MATLAB. I was very excited about it.

    I am willing to give a try on writing a connector to the quote tracker. The TCP/IP tools are available in the instrument control toolbox and I think I can give a try if I get a test password for the quote tracker.

    In the meantime , I have just written some matlab files that work with WSDL. Basically, I connect to their server and get a response of the different "methods" available. So now I can get stock quotes from these FREE websites. One website even gave me the headlines of the news websites that mentioned that Company as a String into MATLAB.!!(very exciting for a newbie like me)

    Please let me know about your desired application and I can give it a try....
     
    #67     Nov 15, 2004
  7. monarc,

    email me at jerry ...at ... quotetracker.com regarding this.
     
    #68     Nov 15, 2004
  8. monarc

    monarc

    hello Jerry,

    i will give you a detailed email reply when I get back home tomorrow afternoon.
     
    #69     Nov 16, 2004
  9. 377OHMS

    377OHMS

    Interesting thread.

    I've been lurking around ET for the last year and have been swing trading about that long, about an hour in the morning before I leave for work. Got a small nut of around 19k.

    Currently I have a manual-order trading rig but have been dreaming of trade automation, black boxs etc.

    My background is BSEE (USC, minor in economics) and I have been writing data analysis routines for the last few years in Matlab. I'm a USAF flight test engineer responsible for avionics flight test of an advanced fighter at Edwards AFB.

    But my mind is on trading, day and night. :D

    For what its worth, I'm currently ranked as a Top-10 World Matlab author by the MathWorks in the data import/export category. I have a routine in the file archives there, autodataread.m, which is considered the fastest ML reader of mixed type ascii data on the planet.

    My particular gimmick is the use of DLLs for performance intensive calculations, calling them from the main Matlab m-file to slurp in data etc as has been mentioned in this thread. I've also got alot of experience with Matlab GUIs and so have been giving some thought to writing a front end for automated trading based upon TA.

    I'm not 100% sure that Matlab is suitable for unsupervised trade automation but think there is enough potential there to test it in a benign account. If anyone cares to collaborate I am in LA and can be reached at res1re94 over at verizon.net.

    regards,
    Scott
     
    #70     Feb 12, 2005