【发布时间】:2021-05-02 05:01:34
【问题描述】:
问题
- 我有 2 个
pd.Series变量,我想合并它们而不重复,保持buy-sell交替顺序。 - 这 2 个 pd.Series 是我交易 Google 和 Apple 股票的交易记录。
- 因为我用所有的钱买了一只股票,所以我在任何时候都只能持有一只股票。因此,连续订单中不能有两次购买。出售时也是如此。我一次性卖出所有数量的单一股票(AAPL 或 GOOG)。
- 我可以在不使用 for 循环的情况下执行此任务吗?
- 下面提供了更详细的代码示例。
代码示例
import pandas as pd
from datetime import datetime
########################
# Google stock trading #
########################
google_index_list = [datetime(2020,1,2,2), datetime(2020,1,2,12), datetime(2020,1,3,7), datetime(2020,1,4,2)]
google_transaction_list = ['buy', 'sell', 'buy', 'sell']
google_trade_series = pd.Series(data=google_transaction_list, index=google_index_list)
#######################
# Apple stock trading #
#######################
apple_index_list = [datetime(2020,1,2,12), datetime(2020,1,2,14), datetime(2020,1,4,3), datetime(2020,1,4,9)]
apple_transaction_list = ['buy', 'sell', 'buy', 'sell']
apple_trade_series = pd.Series(data=apple_transaction_list, index=apple_index_list)
google_trade_series
>> 2020-01-02 02:00:00 buy
2020-01-02 12:00:00 sell
2020-01-03 07:00:00 buy
2020-01-04 02:00:00 sell
apple_trade_series
>> 2020-01-02 12:00:00 buy
2020-01-02 14:00:00 sell
2020-01-04 03:00:00 buy
2020-01-04 09:00:00 sell
############################
# Merging two trade_series #
############################
merged_trade_series = pd.concat([google_trade_series, apple_trade_series])
merged_trade_series.sort_index(inplace=True)
merged_trade_series
>> 2020-01-02 02:00:00 buy
2020-01-02 12:00:00 sell
2020-01-02 12:00:00 buy
2020-01-02 14:00:00 sell
2020-01-03 07:00:00 buy
2020-01-04 02:00:00 sell
2020-01-04 03:00:00 buy
2020-01-04 09:00:00 sell
变量merged_trade_series有2个问题。
- 第一个问题:我们有 2 行具有相同的日期时间
2001-01-02 12:00:00。由于我已经拥有我在 2020-01-02 02:00:00 买入的 Google 股票,我应该采取的行动是“卖出”。所以应该删除“购买”行。 - 第二个问题:我没有在2001-01-02 12:00:00买股票,我在
2001-01-02 14:00:00没有任何股票可以卖。所以这个“卖出”行也应该被删除。
因此,所需的merged_trade_series如下:
desired_trade_series
>> 2020-01-02 02:00:00 buy
2020-01-02 12:00:00 sell
2020-01-03 07:00:00 buy
2020-01-04 02:00:00 sell
2020-01-04 03:00:00 buy
2020-01-04 09:00:00 sell
【问题讨论】:
标签: python pandas datetime concatenation