首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在金融资产DataFrame中将买入日与下一个卖出日配对

如何在金融资产DataFrame中将买入日与下一个卖出日配对
EN

Stack Overflow用户
提问于 2022-03-27 16:56:33
回答 1查看 97关注 0票数 0

我有一个DataFrame,它有收盘价和金融资产的买卖信号。我的目标是创建一个新的数据,与对买卖天。

目前,我通过迭代原始的DataFrame并保存价值和购买日来创建这个新的DataFrame。

代码语言:javascript
复制
import pandas as pd

df = pd.DataFrame({
    'close': [30.0,29.39,29.24,22.2,19.01,26.9,13.92,5.05,13.11,14.94,16.33,14.57,15.91,21.06,22.05,
              24.66,18.96,6.6,5.35,7.76],
    'buy_signal': [False,False,True,False,False,False,False,False,True,True,False,False,False,False,
                   False,False,True,False,False,True],
    'sell_signal': [True,False,False,False,True,True,True,False,False,False,False,False,False,True,
                    False,False,False,False,False,False],
})

df['date'] = ['2022-02-28','2022-03-01','2022-03-02','2022-03-03','2022-03-04','2022-03-07',
              '2022-03-08','2022-03-09','2022-03-10','2022-03-11','2022-03-14','2022-03-15',
              '2022-03-16','2022-03-17','2022-03-18','2022-03-21','2022-03-22','2022-03-23',
              '2022-03-24','2022-03-25',]

df = df.set_index('date')



def get_positions(dt):
    positions = {
        'buy_price': [],
        'sell_price': [],
        
        'buy_date': [],
        'sell_date': [],
    }

    buying = False

    for row in df.itertuples():
        if buying is False and row.buy_signal is True:
            buying = True
            positions['buy_date'].append(row.Index)
            positions['buy_price'].append(row.close)
        
        if buying is True and row.sell_signal is True:
            buying = False
            positions['sell_date'].append(row.Index)
            positions['sell_price'].append(row.close)


    positions['buy_price'] = positions['buy_price'][:len(positions['sell_price'])]
    positions['buy_date'] = positions['buy_date'][:len(positions['sell_date'])]

    positions = pd.DataFrame(positions)
    positions['profit'] = positions['sell_price'] - positions['buy_price']

    return positions


positions = get_positions(df)
positions

尽管这种方法有效,但我发现迭代DataFrame是一种反模式。和一个非常慢的例程用于非常大的DataFrames。

因此,我想知道是否有其他方式来做这些买卖日对。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-27 19:37:18

我认为您可以将dataframe拆分为sell (在下面代码中是df_sell),然后购买(在下面代码中是df_buy)信号,然后使用阿斯forward方向合并它们,然后用NaN过滤掉行。

代码语言:javascript
复制
def get_positions(df):
    df.index = pd.to_datetime(df.index)
    df['date_col'] = df.index
    df_buy = df.loc[df['buy_signal'] == True]
    df_sell = df.loc[df['sell_signal'] == True]

    df_positions = pd.merge_asof(left=df_buy, right=df_sell, right_index=True, left_index=True, direction='forward')
    df_positions.drop_duplicates(subset=['date_col_y'], keep='first', inplace=True)
    df_positions.dropna(inplace=True)


    positions = pd.DataFrame({
        'buy_price': df_positions['close_x'],
        'sell_price': df_positions['close_y'],
        'buy_date': df_positions['date_col_x'],
        'sell_date': df_positions['date_col_y'],
        'profit': df_positions['close_y'] - df_positions['close_x'] })

    return positions

如果还希望保留与之前相同的购买日期(示例数据中的日期为2022-03-11),则可以删除行。

代码语言:javascript
复制
df_positions.drop_duplicates(subset=['date_col_y'], keep='first', inplace=True)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71638389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档