版本比较
If You Knew Tomorrow’s Stock Prices—— Dynamic Programming in Trading
正文
增加 87 行删除 109 行
1234567891011121314151617181920212223242526272829303132333435363738394041424344454618 行未改动6566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219# If You Knew Tomorrow’s Stock Prices—— Dynamic Programming in Trading## IntroductionImagine 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 ModelsSuppose we know the stock prices for the next $T$ days.On day $i$ :- the buying price of one stock is $AP_i$ ;- the selling price of one stock is $BP_i$;- we can buy at most $AS_i$ stocks;- we can sell at most $BS_i$ stocks.There are also two restrictions:1. The number of stocks we hold cannot exceed $P$.2. After completing a transaction, we must wait for $W$ 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 $i$ 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 State18 行未改动$$because they cannot contribute to any valid solution.Now the original problem is transformed into a process of continuously updating these states.---## State TransitionOn each day, there are three possible actions.### 1. Do NothingIf we do not trade today, the number of stocks remains unchanged:$$dp[i][j]=\max(dp[i][j],dp[i-1][j])$$---### 2. Buying StocksBecause of the waiting period, if we buy on day $i$, the previous transaction must have happened before day:$$i-W-1$$Assume that before buying we owned $k$ stocks. After buying $j-k$ stocks, our profit becomes:$$dp[i-W-1][k]-(j-k)AP_i$$Therefore:$$dp[i][j]=\max_k\left\{dp[i-W-1][k]-(j-k)AP_i\right\}$$where:$$0\le j-k\le AS_i$$---### 3. Selling StocksSimilarly, if we sell stocks on day $i$:$$dp[i][j]=\max_k\left\{dp[i-W-1][k]+(k-j)BP_i\right\}$$where:$$0\le k-j\le BS_i$$These transitions completely describe all possible decisions.However, directly enumerating every possible $k$ requires:$$O(TP^2)$$time, which is too slow for large constraints.---## Optimizing with Monotonic QueueThe 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)AP_i$$It can be rewritten as:$$(dp[i-W-1][k]+kAP_i)-jAP_i$$For a fixed day $i$, the term:$$-jAP_i$$is constant.Therefore, we only need to find the maximum value of:$$dp[i-W-1][k]+kAP_i$$inside a valid interval of $k$.As $j$ 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)$$which makes the problem solvable even for much larger inputs.---## The Bigger PictureThe 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.123456789101112131415161718192021222324252627282930313233343536373818 行未改动57585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197# If You Knew Tomorrow’s Stock Prices — Dynamic Programming in Trading## IntroductionSuppose you knew the exact stock prices for every day of the next few months. Would it then be easy to decide when to buy and sell?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 explains how dynamic programming finds the most profitable trading strategy without trying every possible sequence of trades.---## From Trading Decisions to Mathematical ModelsWe follow a few trading rules. The account can hold up to $P$ shares at a time. After buying or selling, we must wait $W$ full days before trading again. For example, if $W=1$ and we trade on day 1, we can next trade on day 3.Besides $P$ and $W$, suppose we also know the stock prices for the next $T$ days.- the buying price per share is $AP_i$;- the selling price per share is $BP_i$;- we can buy at most $AS_i$ shares;- we can sell at most $BS_i$ shares.We begin with no shares and enough money to cover our purchases. The buying price is at least the selling price on each day. The goal is to maximize the final profit: the total money received from sales minus the total money spent on purchases.A straightforward idea is to enumerate every possible sequence of buying and selling. However, the number of possible strategies can grow exponentially with time, making this approach impractical even for relatively short periods.The key observation is that many different trading histories can lead to the same situation.For example, suppose two strategies reach the same day with the same number of shares, and both have finished their waiting periods. From then on, they have the same trading options. If one has earned less than the other, it cannot produce a better final result by following the same future trades.This leads to the central idea of dynamic programming:> We do not need to remember every past transaction. We need to keep the information that affects future decisions.---## Defining the State18 行未改动$$because they cannot contribute to any valid solution.We can now solve the problem by using state transitions to calculate $dp[i][j]$ from earlier states.---## State TransitionOn each day, there are three possible actions.### 1. Do NothingIf we do not trade today, the number of shares remains unchanged. We first set:$$dp[i][j]=dp[i-1][j].$$We then check whether buying or selling can give a better result.### 2. Buying SharesIf we buy on day $i$, the previous transaction must have happened no later than day $i-W-1$.Assume that before buying we owned $k$ shares. After buying $j-k$ shares, our net cash income becomes:$$dp[p][k]-(j-k)AP_i.$$Therefore, for every valid $k$, we update:$$dp[i][j]\leftarrow\max\left\{dp[i][j],dp[p][k]-(j-k)AP_i\right\},$$where:$$\max(0,j-AS_i)\le k<j.$$This range ensures that we buy at least one share and no more than today's buying allowance.### 3. Selling SharesSimilarly, if we sell $k-j$ shares on day $i$, we update:$$dp[i][j]\leftarrow\max\left\{dp[i][j],dp[p][k]+(k-j)BP_i\right\},$$where:$$j<k\le\min(P,j+BS_i).$$These three cases cover every legal trading schedule. If a transaction happens today, all earlier transactions must finish by day $p$, so their best result is already available in the table.The final answer is:$$dp[T][0].$$There is no benefit to ending with unsold shares when we count only cash income: omitting the purchases of those leftover shares would save money without changing the completed sales.There are $O(TP)$ states, and each state checks at most $O(P)$ previous holdings. The total running time is:$$O(TP^2).$$The table uses $O(TP)$ memory, or about $8TP$ bytes with 64-bit integers. When $TP^2$ is around $10^7$ or less, the computation will typically finish within about a second on a modern computer.---## The Bigger PictureOur DP finds the maximum profit without checking every possible sequence of trades. By reusing the best results for earlier states, it avoids much of the repeated work in brute-force enumeration.To run it, we need $T$, the number of days; $P$, the maximum number of shares we can hold; and $W$, the number of full days we must wait after each transaction. For each day $i$, we also need the buying and selling prices, $AP_i$ and $BP_i$, and the maximum quantities we can buy and sell, $AS_i$ and $BS_i$. When $TP^2$ is around $10^7$ or less, this approach is usually fast enough for a short run on a modern computer.Here is a C++ implementation you can try in VS Code with a C++ compiler installed. This version allows up to 500 days and 500 shares. You can increase the array size by changing $N$ in the code, keeping it larger than both $T$ and $P$. However, large values of $TP$ require more memory, and large values of $TP^2$ take longer to compute.Enter $T$, $P$, and $W$ on the first line, followed by $T$ lines containing $AP_i$, $BP_i$, $AS_i$, and $BS_i$.```cpp#include <bits/stdc++.h>using namespace std;typedef long long ll;const int N=505;const ll INF=1e18;int t,p,w,ap,bp,as,bs;ll dp[N][N];int main() {ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);cin>>t>>p>>w;for (int i=0;i<=t;i++)for (int j=0;j<=p;j++) dp[i][j]=-INF;dp[0][0]=0;for (int i=1;i<=t;i++) {cin>>ap>>bp>>as>>bs;int pre=max(0,i-w-1);for (int j=0;j<=p;j++) {dp[i][j]=dp[i-1][j];for (int k=max(0,j-as);k<j;k++) {if (dp[pre][k]==-INF) continue;dp[i][j]=max(dp[i][j],dp[pre][k]-1ll*(j-k)*ap);}for (int k=j+1;k<=j+min(bs,p-j);k++) {if (dp[pre][k]==-INF) continue;dp[i][j]=max(dp[i][j],dp[pre][k]+1ll*(k-j)*bp);}}}cout<<dp[t][0]<<'\n';return 0;}```The program prints the maximum profit after $T$ days.Beyond trading, dynamic programming helps businesses plan inventory and reduce ordering and storage costs. It is also used to calculate shortest paths in networks and align DNA sequences to identify similarities. The states and transitions change, but reusing earlier results remains central to each application.