New Forum

Visit the new forum at http://godelsmarket.com/bb

Saturday, July 28, 2012

MATLAB VWAP

Here's a simple MATLAB script to extract data from a MySQL Database (here, specifically one that was created using my IB historical data extractor) and plot close data along with two VWAPs (volume weighted average prices) of your desired length. It's pretty simple but could be expanded upon to backtest VWAP strategies using the created VWAP matrices. (Also, I think I fixed the way source code is displayed on this site...should now be easier to copy and paste).

Update: Here's part II.

clear close_mat
clear volume_mat
clear vwap
clear vwap_2

vwap_length = 100;
vwap_length_2 = 500;

format long

%connect to the database
conn = database('stocks','root','***','com.mysql.jdbc.Driver','jdbc:mysql://localhost:3306/stocks');

%query the symbols in the database
str_query_close = 'SELECT close, volume FROM stock_prices_minute WHERE symbol = ''GOOG''';
close_cell = fetch(conn, str_query_close);

close_mat = cell2mat(close_cell(:,1))
volume_mat = cell2mat(close_cell(:,2));

close_times_volume = close_mat .* volume_mat;


for i = vwap_length:length(close_times_volume)
    volume_total = 0;
    volume_price_sum = 0;
    for j = 0:(vwap_length - 1)
        volume_total = volume_total + volume_mat(i-j);
        volume_price_sum = volume_price_sum + volume_mat(i-j)*close_mat(i-j);
    end
    vwap(i-(vwap_length - 1)) = volume_price_sum / volume_total;
end

for i = vwap_length_2:length(close_times_volume)
    volume_total = 0;
    volume_price_sum = 0;
    for j = 0:(vwap_length_2 - 1)
        volume_total = volume_total + volume_mat(i-j);
        volume_price_sum = volume_price_sum + volume_mat(i-j)*close_mat(i-j);
    end
    vwap_2(i-(vwap_length_2 - 1)) = volume_price_sum / volume_total;
end


x = [1:length(close_mat)];
x2 = [(vwap_length):length(close_mat)];
x3 = [(vwap_length_2):length(close_mat)];
plot(x, close_mat)
hold on
plot(x2, vwap, '-r')
hold on
plot(x3, vwap_2, '-g')

No comments:

Post a Comment