我一直在尝试编写一些基于“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)
此外,但不是必要的,而不是使用一个二进制系统作为链接上面显示的买卖,有可能引入另一个整数来显示交易者持有(既不买也不卖)?你知道吗
您可以使用动态规划来计算最佳利润,如下所示:
输出:
160与您描述的最佳解决方案匹配。有关解决方案的两个重要注意事项:
memory
dic来记忆反复出现的子问题。你知道吗相关问题 更多 >
编程相关推荐