Main Content

Implement a Financial Strategy by Using Stateflow

This example shows how to use a standalone Stateflow® chart to model a financial trading strategy known as Bollinger Bands. Standalone charts implement classic chart semantics with MATLAB® as the action language. You can program the chart by using the full functionality of MATLAB, including those functions that are restricted for code generation in Simulink®. For more information, see Create Stateflow Charts for Execution as MATLAB Objects.

Compute Bollinger Bands

The Bollinger Bands trading strategy is to maintain a moving average of N stock prices for some commodity and issuing trading instructions depending on the value of the stock:

  • "Buy" when the value of the stock drops K standard deviations below the moving average.

  • "Sell" when the value of the stock rises K standard deviations above the moving average.

  • "Hold" when the value of the stock is within K standard deviations of the moving average.

Typical implementations for this strategy use values of N = 20 and K = 2.

The file sf_stock_watch.sfx defines a standalone Stateflow chart that implements this financial strategy. The chart consists of two outer states in parallel decomposition.

  • The StockTicker subchart records the current price of a stock. The subchart hides the details for calculating stock prices. To access real-time market data from financial data providers, one possible implementation involves the use of the Datafeed Toolbox™. For details, see Datafeed Toolbox.

  • The FinancialAdvisor state uses the last N stock prices to compute high and low bands. Depending on the current price relative to these bands, the state generates "buy," "sell," or "hold" instructions. The action on every(1,sec) creates a MATLAB® timer to execute the chart every second. See Control Chart Execution by Using Temporal Logic.

Parallel decomposition is a common design pattern that enables your algorithm to preprocess input data. For more information, see Define Exclusive and Parallel Modes by Using State Decomposition.

Execute Standalone Chart

To execute the standalone chart, create a Stateflow chart object w:

w = sf_stock_watch();

The chart generates a stream of stock prices and issues "buy," "sell," or "hold" instructions.

Note: Chart execution continues until you delete the chart object.
Loading data... Ready in 5 4 3 2 1 0:
HOLD at 14.1942
SELL at 14.2802
SELL at 14.2471
HOLD at 14.2025
BUY at 14.1444

To stop the chart execution, delete the chart object w:

delete(w);

Related Topics