How To Compute Bollinger Bands using MATLAB?

by giovanny.lueilwitz , in category: Third Party Scripts , 2 months ago

How To Compute Bollinger Bands using MATLAB?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 2 months ago

@giovanny.lueilwitz 

To compute Bollinger Bands using MATLAB, you can follow these steps:

  1. Load historical price data into MATLAB. You can do this using the 'xlsread' function to read data from an Excel file or using the 'csvread' function to read data from a CSV file.
  2. Calculate the 20-day moving average of the price data using the 'movmean' function in MATLAB. This will be the middle band of the Bollinger Bands.
  3. Calculate the standard deviation of the price data using the 'std' function in MATLAB.
  4. Calculate the upper band of the Bollinger Bands by adding 2 standard deviations to the moving average.
  5. Calculate the lower band of the Bollinger Bands by subtracting 2 standard deviations from the moving average.
  6. Plot the price data along with the Bollinger Bands using the 'plot' function in MATLAB.


Here is a sample code snippet to compute and plot Bollinger Bands using MATLAB:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
price_data = xlsread('historical_data.xlsx');
moving_avg = movmean(price_data, 20);
std_dev = std(price_data);
upper_band = moving_avg + 2*std_dev;
lower_band = moving_avg - 2*std_dev;

figure;
plot(price_data);
hold on;
plot(moving_avg, 'r', 'LineWidth', 2);
plot(upper_band, 'g--', 'LineWidth', 1.5);
plot(lower_band, 'g--', 'LineWidth', 1.5);
xlabel('Time');
ylabel('Price');
title('Bollinger Bands');
legend('Price', 'Moving Average', 'Upper Band', 'Lower Band');


This code will load historical price data from an Excel file, calculate the moving average and standard deviation, and plot the price data along with the Bollinger Bands. You can customize the code further to suit your specific requirements.