Django
Django

Reputation: 363

Maximising stock profit given multiple stocks

I have looked into stock profit maximising algorithms depending on the situation.

Strategies for situations where you only have one stock and can either buy/sell once or multiple times are clear to me. You use greatest difference and maximum sub array respectively.

But what happens when given two stocks and their respective fluctuating prices? You cannot hold both stocks at the same time and selling one and buying another introduces a transaction cost.

Example: Maximise returns given Stocks A and B. The stocks prices fluctuate from period to period. So if given an array, the indices in each array for A and B indicate the price of the stock at a particular time. Considering that you cannot hold both stocks at the same time and buying A and selling B induces a transaction cost, what's the best strategy to use?

Upvotes: 3

Views: 1329

Answers (1)

IVlad
IVlad

Reputation: 43477

Let:

dp[i, j] = maximum worth obtainable at period i if we currently hold 
           stock j

Assume t[i] = transaction cost at period i.

We have:

dp[0, A] = A[0] # buy the best at time 0
dp[0, B] = B[0] # you said only buying A and selling B induces a cost,
                # you didn't say buying B induces a cost. If it does,
                # just subtract t accordingly below
dp[i, A] = max(
             dp[i - 1, B] + A[i] - t[i], # sell B, buy A
             A[i]                        # buy A alone
           )                             # we buy A no matter what

dp[i, B] = max(
             dp[i - 1, A] + B[i],        # sell A, buy B, - t[i] if needed
             B[i]                        # buy B alone
           )

Answer is:

max{dp[i, A], dp[i, B]}
 i

Upvotes: 1

Related Questions