2012-10-21 30 views
1

我刚刚开始使用Python并使用熊猫来编写一个股票投资组合应用程序。我遇到的问题是在我的职位类别中,该类职位创建了熊猫系列来根据交易来表示随着时间的推移,每只股票拥有的股份数量。因此,如果我在2012年10月10日在IBM购买50股股票并在10/14/2012卖出10股,我希望IBM的position.shares系列是:熊猫添加系列以保持运行总和

  • 10/10/2012:50
  • 2012年10月11日:50
  • 2012年10月12日:50
  • 2012年10月13日:50
  • 2012年10月14日:40
  • 2012年10月15日:40

我计划通过添加从交易日期到当前日期的系列,然后将每个系列汇总为一个系列。我正在尝试使用Series.add函数,因为我需要一个填充值来确保表示新事务的新共享序列不是NaN旧位置。问题是我不知道如何初始化可以正确添加的可用系列。我想系列(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   

感谢您的帮助。如果我缺少一些非常基本的东西,我很抱歉。

+2

你有小样本有这个问题,可以复制粘贴和尝试。 – Himanshu

回答

1

so Series.add 返回总结的系列...我认为它只是将它添加到已有的Series对象中。所以我这样做:

self.shares = self.shares.add(shareSer, fill_value=0) 

,而不是

self.shares.add(shareSer, fill_value=0) 

和它的作品。