我正在尝试构建一个脚本来模拟销售股票的策略。出于对股票价格的假设,随着时间的推移,目的是以更高的价格出售越来越多的股票。多个卖单定期(每周)创建并保持开放,直到它们以高于其限价的价格进行填充(限价是我愿意卖出股票的价格)。每个卖单都有不同的限价,因此价格越高,订单越多,卖出的库存越多。
我的方法是使用列表来反映每周价格假设和列表,以反映每周下达的订单。我的意图是每周迭代订单清单并“填写”符合以下条件的订单:
这是脚本的简化版本
orders = [] # initalize an empty list of orders. Append orders to this list each week.
number_of_weeks = 4 # number of weeks to simulate
weekly_order_template = [[100, 5, "", ""],[150, 10, "", ""]] # these are the orders that will be added each week (2 in this example) and each order includes the number of shares, the limit price, the sale price (if sold), the sale week (if sold).
# create a list to store the weekly price assumptions
weekly_price = [] # init a list to store weekly prices
price = 4.90
price_increment = .05
for weeks in range(0,number_of_weeks):
price = price + price_increment
weekly_price.append(price)
# each week, add this week's orders to the orders list and then compare all orders in the list to see which should be sold. Update the orders list elements to reflect sales.
for week in range(0,number_of_weeks):
print "****This is WEEK ", week, "****"
this_weeks_price = weekly_price[week]
print "This week's price: ", this_weeks_price
for order in weekly_order_template: # add this week's orders to the orders list
orders.append(order)
for order in orders: # iterate over the orders list and update orders that are sold
if (order[2] == "") and (order[1] < this_weeks_price):
order[2] = this_weeks_price
order[3] = week
print "All orders to date: ", orders
此脚本无效。在这些订单存在之前,它是“卖出”订单。例如,这是第四周的输出:
****This is WEEK 3 ****
This week's price: 5.1
All orders to date: [[100, 5, 5.05, 2], [150, 10, '', ''], [100, 5, 5.05, 2], [150, 10,'', ''], [100, 5, 5.05, 2], [150, 10, '', ''], [100, 5, 5.05, 2], [150, 10, '', '']]
为什么第七个元素(第3周的第一个订单)在前一周的价格而不是当时的5.10美元价格“卖出”? (注意 - “WEEK 3”是指自从我将第0周用作第一周以来的第四周)
答案 0 :(得分:1)
Python使用“引用语义”,换句话说,它永远不会复制某些东西,除非你告诉它明确地这样做。
问题在于这一行:
orders.append(order)
它将order
引用的对象追加到列表中,然后在下一周它再次附加同一个对象。你应该做的是附上一份副本:
orders.append(list(order))
答案 1 :(得分:0)
更改行
orders.append(order)
到
orders.append(list(order))
问题是您需要从weekly_order_template
创建订单的副本(这是list(order)
所做的),而不是简单地引用订单模板,以便以后更改订单时(在for order in orders:
循环中)您要更改订单模板的各个副本,而不是订单模板本身。