繁体   English   中英

遍历扩展列表/嵌套循环

[英]Iterating over expanding list / nested for loops

我正在尝试构建一个脚本来模拟出售股票的策略。 考虑到有关股票价格随时间的假设,其意图是以更高的价格出售越来越多的股票。 定期(每周)创建多个卖单,并保持打开状态,直到以高于其极限价的价格(极限价是我愿意出售股票的价格)成交为止。 每个卖单都有不同的限价,因此,以更高的价格可以成交更多的订单,卖出更多的库存。

我的方法是使用一个列表来反映每周的价格假设,并使用一个列表来反映每周下的订单。 我的意图是每周遍历订单列表并“填写”满足以下条件的订单:

  • 他们的限价低于该周的价格假设
  • 他们尚未出售

这是脚本的简化版本

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“卖出”的? (注意-“第3周”指的是第四周,因为我将第0周用作第一周)

Python使用“引用语义”,换句话说,除非您明确指示要这样做,否则它绝不会复制任何内容。

问题在于此行:

orders.append(order)

它将按order引用的对象附加到列表,然后在下周再次将相同的对象附加。 您应该做的是附加一个副本:

orders.append(list(order))

换线

orders.append(order)

orders.append(list(order))

问题在于,您需要从weekly_order_template创建订单的副本(这是list(order)所做的事情),而不是简单地引用订单模板,以便稍后更改订单时(在订单中的for order in orders:循环),您将更改订单模板的单个副本,而不是订单模板本身。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM