跳到正文

个人记录

If You Knew Tomorrow’s Stock Prices—— Dynamic Programming in Trading

EchoHua0402约 11 分钟
原文

这是 2026年10月2日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年10月2日
收录
2026年10月2日
更新
2026年11月9日
篇幅
约 11 分钟

版本

  1. v2当前
  2. v1

If You Knew Tomorrow’s Stock Prices—— Dynamic Programming in Trading

Introduction

Imagine a world where the future is no longer a mystery. Before the market opens, you already know the exact stock prices of every day in the following months. Would becoming a perfect trader finally become easy?

Surprisingly, the answer is still no.

Knowing the future removes uncertainty, but it does not remove the difficulty of decision-making. When every choice changes the possibilities of future choices, finding the optimal strategy becomes an algorithmic problem.

This article shows how dynamic programming turns an overwhelming number of possible strategies into a tractable optimization problem.


From Trading Decisions to Mathematical Models

Suppose we know the stock prices for the next TT days.

On day ii :

  • the buying price of one stock is APiAP_i ;
  • the selling price of one stock is BPiBP_i;
  • we can buy at most ASiAS_i stocks;
  • we can sell at most BSiBS_i stocks.

There are also two restrictions:

  1. The number of stocks we hold cannot exceed PP.

  2. After completing a transaction, we must wait for WW days before making another transaction.

The goal is to maximize the final profit.

A straightforward idea is to enumerate every possible sequence of buying and selling. However, the number of possible strategies grows exponentially with time, making brute force impossible.

The key observation is that many different trading histories can lead to exactly the same situation.

For example, suppose two strategies arrive at day ii while holding the same number of stocks. From this moment onward, they face exactly the same choices. Therefore, if one strategy has already earned less profit than the other, it will never become better in the future.

This leads to the central idea of dynamic programming:

We do not need to remember every path that happened before. We only need to remember the information that affects future decisions.


Defining the State

To describe a trading situation, we only need two pieces of information:

  • the current day;
  • the number of stocks currently held.

Let dp[i][j]dp[i][j] represent the maximum profit after day ii, when we own exactly jj stocks.

Initially, we have no stocks and no profit:

dp[0][0]=0dp[0][0]=0

All unreachable states are assigned:

−∞-\infty

because they cannot contribute to any valid solution.

Now the original problem is transformed into a process of continuously updating these states.


State Transition

On each day, there are three possible actions.

1. Do Nothing

If we do not trade today, the number of stocks remains unchanged:

dp[i][j]=max⁡(dp[i][j],dp[i−1][j])dp[i][j]=\max(dp[i][j],dp[i-1][j])

2. Buying Stocks

Because of the waiting period, if we buy on day ii, the previous transaction must have happened before day:

i−W−1i-W-1

Assume that before buying we owned kk stocks. After buying j−kj-k stocks, our profit becomes:

dp[i−W−1][k]−(j−k)APidp[i-W-1][k]-(j-k)AP_i

Therefore:

dp[i][j]=max⁡k{dp[i−W−1][k]−(j−k)APi}dp[i][j] = \max_k \left\{ dp[i-W-1][k]-(j-k)AP_i \right\}

where:

0≤j−k≤ASi0\le j-k\le AS_i

3. Selling Stocks

Similarly, if we sell stocks on day ii:

dp[i][j]=max⁡k{dp[i−W−1][k]+(k−j)BPi}dp[i][j] = \max_k \left\{ dp[i-W-1][k]+(k-j)BP_i \right\}

where:

0≤k−j≤BSi0\le k-j\le BS_i

These transitions completely describe all possible decisions.

However, directly enumerating every possible kk requires:

O(TP2)O(TP^2)

time, which is too slow for large constraints.


Optimizing with Monotonic Queue

The reason the transition is slow is that we repeatedly search for the maximum value inside a moving range.

Consider the buying transition:

dp[i−W−1][k]−(j−k)APidp[i-W-1][k]-(j-k)AP_i

It can be rewritten as:

(dp[i−W−1][k]+kAPi)−jAPi(dp[i-W-1][k]+kAP_i)-jAP_i

For a fixed day ii, the term:

−jAPi-jAP_i

is constant.

Therefore, we only need to find the maximum value of:

dp[i−W−1][k]+kAPidp[i-W-1][k]+kAP_i

inside a valid interval of kk.

As jj increases, this interval moves continuously, which creates a sliding window maximum problem.

A monotonic queue maintains the best candidates efficiently:

  • outdated states are removed from the front;
  • states that can never become optimal are removed from the back;
  • the maximum candidate is always kept at the front.

Since every state enters and leaves the queue at most once, each transition is processed in linear time.

The final complexity is reduced to:

O(TP)O(TP)

which makes the problem solvable even for much larger inputs.


The Bigger Picture

The stock market scenario is only a metaphor for a much broader class of problems in computer science.

The real challenge is not always the lack of information. Sometimes, even when all information is available, the number of possible decisions is simply too large to explore directly.

Dynamic programming provides a way to handle this complexity. It divides a difficult problem into smaller states, identifies repeated structures, and stores only the information that can influence future decisions.

In this problem, the algorithm does not search for the best individual transaction. Instead, it considers the entire sequence of decisions and proves that the optimal answer can be constructed from optimal states that have already been solved.

This idea appears in many areas beyond trading. Route planning, resource allocation, artificial intelligence, and biological data analysis all contain problems where many possible choices share common structures.

The most important lesson is that algorithms do not create information or predict the future. They organize knowledge and reveal hidden patterns.

Even when tomorrow’s stock price is already known, the hardest part is still deciding what to do.

And that is exactly where algorithms begin to think.