我刚开始使用Python并使用pandas编写一个小股票投资组合应用程序。我遇到的问题是在我的职位类别中创建了大熊猫系列,以表示基于交易的每个股票随时间变化所拥有的股票数量。因此,如果我在10月12日在IBM购买50股股票并在10/14/2012卖出10股,我希望IBM的position.shares系列是:
我计划通过添加从交易日期到当前日期的系列,然后将这些系列中的每一个相加为一个来实现此目的。我正在尝试使用Series.add函数,因为我需要一个填充值来确保代表新事务的新股票系列不是NaN的旧头寸。问题是我不知道如何初始化可以正确添加的可行系列。我在下面的代码中尝试使用Series(0),只返回:
Series([], dtype=float64)
我也尝试用一些0值的随机日期来初始化它,但是即使在添加了不同的系列之后,我仍然继续获得该系列。
这是我的代码:
class Position:
def __init__(self, trades):
self.ticker = trades[0].ticker #grab the ticker we are dealing with
self.shares = Series()
for trade in trades:
if trade.tranType == 0 or trade.tranType == 2:
direction = 1 #a buy increases share amount
else:
direction = -1 # a sell decreases share amount
dateRangeInFolio = pd.DateRange(trade.date, datetime.datetime.today()) #from the event date through today
shareSer = Series(trade.shares * direction, index=dateRangeInFolio)
self.shares.add(shareSer, fill_value=0)
print self.shares
感谢您的帮助。如果我遗漏了一些非常基本的东西,我道歉。
答案 0 :(得分:1)
所以Series.add 返回总计系列...我认为它只是将它添加到现有的Series对象中。所以我这样做了:
self.shares = self.shares.add(shareSer, fill_value=0)
而不是
self.shares.add(shareSer, fill_value=0)
它有效。