2012-08-05 67 views
1

我試圖構建一個腳本來模擬銷售股票的策略。考慮到股價隨着時間的推移,其意圖是以更高的價格出售越來越多的股票。多次賣出訂單會定期(每週)創建並保持開放狀態,直到它們的價格高於其限價(限價是我願意出售股票的價格)。每個賣出訂單都有不同的限制價格,因此在更高的價格下可以填充更多的訂單並賣出更多的庫存。迭代擴展列表/嵌套for循環

我的方法是使用一個列表來反映每週價格假設和列表以反映每週放置的訂單。我的目的是要遍歷訂單每週列出和「補」符合以下條件的訂單:

價格假設該周
  • 它們尚未被出售
  • 下面
    • 他們有限房價

    這裏的腳本

    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周後的第四周)

    回答

    1

    Python使用「引用語義」,換句話說,除非您告訴它這樣做,明確。

    問題是這一行:

    orders.append(order) 
    

    其追加對象通過order提到的列表,然後下週再次追加相同的對象。你應該做的是附加的一個副本:

    orders.append(list(order)) 
    
    +0

    謝謝!這個改變確實解決了這個問題,我不知道我是否會自己想出這個問題。 – 2012-08-05 19:17:36

    0

    更改線路

    orders.append(order) 
    

    orders.append(list(order)) 
    

    的問題是,你需要創建命令的副本從weekly_order_template(這是list(order)所做的),而不是簡單地引用訂單模板,以便稍後更改訂單時(在for order in orders:循環中),您ar e更改訂單模板的單個副本,而不是訂單模板本身。

    +1

    謝謝!我讚賞解釋。我還沒有足夠的積分來回答你的答案,但我確實對我有幫助。 – 2012-08-05 19:21:58