【发布时间】:2019-12-22 22:15:29
【问题描述】:
我一直在尝试编写一些基于“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)
另外,但不是必需的,除了使用上面链接显示的二进制系统进行买卖之外,是否可以引入另一个整数来显示交易者何时持有(既不买入也不卖出)?
【问题讨论】:
标签: python optimization