2017-06-18 43 views
2

這是爲了模擬結構性投資中的「敲除」情形。一般來說,有三種股票:股票A;股票B;庫存C,並且每月觀察它們的價格以檢查它們是否高於第一個月的價格(KO水平)的100%。如何在價值大於某物時返回第一個指數

基本數據幀是這樣的:

  Stock-A Stock-B Stock-C 
2010-01-01 10  20  40 
2010-02-01 9.5  18  31 
2010-03-01 10.5 22  39 
2010-04-01 11.5 23  36 

如果他們的價格KO級以上去的一個,函數應該返回月份和不需要監視的價格了。

例如,在2010年3月1日KO級別的股票A,所以函數應該將此標記爲成功的「敲出」股票,並返回日期,即2010-03- 01。

如果有一隻股票從未橫過線,該函數應該迭代結束並將其作爲未被淘汰的股票返回。我怎樣才能做到這一點?

+0

注意:我編輯Stock-C是一個未被淘汰的股票。否則,所有3個被淘汰的股票和答案不能檢查未被淘汰的股票。 – JohnE

+0

謝謝約翰,任何想法如何做到? –

回答

0

這裏是我的嘗試,具有一定的假設條件(加,藉此與一粒鹽:我並不算得上是大熊貓專家,只是認爲這將是一個有趣的問題上下工夫)

df = pandas.DataFrame([ 
    {'date': '2010-01-01', 'stock_a': 10, 'stock_b': 20, 'stock_c': 30}, 
    {'date': '2010-01-02', 'stock_a': 9.5, 'stock_b': 18, 'stock_c': 31}, 
    {'date': '2010-03-01', 'stock_a': 10.5, 'stock_b': 22, 'stock_c': 39}, 
    {'date': '2010-04-01', 'stock_a': 11.5, 'stock_b': 23, 'stock_c': 36}, 
]) 
# Assuming you want the first chronological record of such an event 
df = df.sort_values(['date', 'stock_a', 'stock_b', 'stock_c']) 
df2 = pandas.concat([ 
    df['stock_a'] > df['stock_a'][0], 
    df['stock_b'] > df['stock_b'][0], 
    df['stock_c'] > df['stock_c'][0], 
], axis=1) 
df2['date'] = True 
# At this point columns stock_{a,b,c} are populated with NaN in place where the value 
# was less than the first observation 
df3 = df[df2].query('stock_a == stock_a & stock_b == stock_b & stock_c == stock_c') 

if not df3.empty: 
    print df3.iloc[[0]] 
print 'No match' 
相關問題