股票利润最大化:给定价格阵列,如何利用边界最大化利润

时间:2019-08-16 15:17:25

标签: python optimization

我一直试图基于“ Maximizing profit for given stock quotes”编写一些代码,但是我想对交易者的操作施加某些限制。在我的代码中,我试图将他可以拥有的股票数量限制为N = 4,并且在给定的时间间隔内他可以购买或出售的股票数量为C =1。目标是找到集合给定股价阵列以最大程度地增加利润的行动。

因此对于给定的价格数组

stock_prices = [20,20,20,20,25,30,25,30,25,20,20,30,35,40,45,50,60,60,50,40,35,30,25,20],

最佳地,交易者应该在时间间隔1、2、3和4买入(每个20美元),在时间间隔6和8卖出(每个30美元),在10和11再次买入,然后在所有时间卖出16、17、18和19。在一天结束时,交易者应该拥有零股。

这是我到目前为止尝试过的:

def calcprofit(stock_prices):
    buy=[1]*len(stock_prices) # 1 reflects buy and 0 reflects sell
    profit=0
    m=0
    storage_limit = 4
    c = 1   #Change in shares
    storage = 0
    for i in reversed(range(len(stock_prices))):
        price = stock_prices[i] # shorthand name
        if storage < storage_limit and m <= price:
            buy[i] = 1
            m = price
            storage += c
        if storage >= storage_limit and m >= price:
            buy[i] = 0
            storage -= c
        profit += (m-price)
    return (profit,buy,storage)

当前,代码无法一次出售一只股票,也不能出售或购买由更改确定的金额。目前,我得到的结果是:

(505, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], 3)

另外但不是必须的,不是像上面的链接所示那样使用二进制系统进行买卖,而是可以引入另一个整数来显示交易者何时持有(既不买卖)?

1 个答案:

答案 0 :(得分:0)

您可以使用动态编程来计算最佳利润,如下所示:

stock_prices = [20,20,20,20,25,30,25,30,25,20,20,30,35,40,45,50,60,60,50,40,35,30,25,20]
MAX_STOCKS = 4
memory = {}

def dp(i=0, stockes=0):

  if i == len(stock_prices):
    return 0

  if (i, stockes) in memory:
    return memory[(i, stockes)]

  memory[(i, stockes)] = max(
      dp(i+1, stockes), 
      dp(i+1, stockes+1) - stock_prices[i] if stockes < MAX_STOCKS else -1, 
      dp(i+1, stockes-1) + stock_prices[i] if stockes > 0 else -1)

  return memory[(i, stockes)]


print(dp())

输出:

160

160与您描述的最佳解决方案匹配。有关该解决方案的两个重要说明:

  1. 在每次电话会议中,我都会计算三种可能性:不买卖,如果没有达到限制则购买股票,以及如果我们有至少一个股票则出售股票。
  2. 在动态编程中,问题具有重叠的结构,其中子问题多次出现,因此,我使用memory dic来记住重复出现的子问题。