我試圖構建一個腳本來模擬銷售股票的策略。考慮到股價隨着時間的推移,其意圖是以更高的價格出售越來越多的股票。多次賣出訂單會定期(每週)創建並保持開放狀態,直到它們的價格高於其限價(限價是我願意出售股票的價格)。每個賣出訂單都有不同的限制價格,因此在更高的價格下可以填充更多的訂單並賣出更多的庫存。迭代擴展列表/嵌套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周後的第四周)
謝謝!這個改變確實解決了這個問題,我不知道我是否會自己想出這個問題。 – 2012-08-05 19:17:36