Beispiel #1
0
def construct_ranking_table(portfolio,lookbackDays=None,oldTable=None,enddate=dt.today(),index=None,silent=False):
  dfarr = []
  for stock in portfolio.stocks:
    if index == None:
      idx = getdata.getIndexTicker(getdata.getData([stock.ticker],getdata.getParamDict('stock exchange')))
    else:
      idx = index
    indexCurrVal = getdata.get_history([idx],
                                          dt.today()-relativedelta(days=5))[-1:]['Close'].values[0]
    try:
      indexPrevVal = oldTable.ix[stock.ticker]['%Gain Index (Period)']
    except:
      indexPrevVal = getdata.get_history([idx],
                                          dt.today()-relativedelta(days=lookbackDays))['Close'].values[0]
    dftemp = pd.DataFrame(data=[0],index=[0])
    #dftemp['Date'] = dt.today()
    dftemp['Symbol'] = stock.ticker
    dftemp['Name'] = getdata.getData([stock.ticker],"n")
    dftemp['Price'] = getdata.get_history([stock.ticker],
                                          dt.today()-relativedelta(days=5))[-1:]['Close'].values[0]
    dftemp['Number Owned'] = stock.shares_owned
    dftemp['Current Value'] = dftemp['Price']*dftemp['Number Owned']
    try:
      dftemp['Previous Value'] = oldTable.ix[stock.ticker]['Current Value']
    except:
      dftemp['Previous Value'] = dftemp['Number Owned']*getdata.get_history([stock.ticker],
                                          dt.today()-relativedelta(days=lookbackDays))['Close'].values[0]
    dftemp['%Gain (Period)'] = 100*(dftemp['Current Value'] - dftemp['Previous Value'])/dftemp['Previous Value']
    dftemp['%Gain Index (Period)'] = 100*(indexCurrVal - indexPrevVal)/indexPrevVal
    dftemp['Index'] = idx
    dftemp['GainSt - GainIdx'] = dftemp['%Gain (Period)'] - dftemp['%Gain Index (Period)']
    #if dftemp['%Gain Index (Period)'] > dftemp['%Gain (Period)']:
    #  dftemp['Stock > Index'] = 'N'
    #else:
    #  dftemp['Stock > Index'] = 'Y'
    dftemp['Total Investment'] = stock.investment
    dftemp['%Total Gain'] = 100*(dftemp['Current Value'] - stock.investment)/stock.investment
    dftemp = dftemp.drop(0,axis=1)
    dftemp.index = dftemp['Symbol']
    dftemp = dftemp.drop('Symbol',axis=1)
    dfarr.append(dftemp)
  dftoret = pd.concat(dfarr)
  #dftoret = dftoret.sort(columns='Stock > Index',ascending=False)
  dftoret = dftoret.sort(columns='GainSt - GainIdx',ascending=False)
  dftoret = dftoret.drop('GainSt - GainIdx',axis=1)
  dftoret['Rank'] = range(1,len(dftoret)+1)
  if not silent:
    print "Stocks doing better than the market:",dftoret[dftoret['%Gain (Period)']>dftoret['%Gain Index (Period)']].index.values
    print "Stocks doing worse than the market:",dftoret[dftoret['%Gain (Period)']<dftoret['%Gain Index (Period)']].index.values
  return dftoret
Beispiel #2
0
    def getHistory(self,start_date):
        tickers = []
        for stock in self.stocks:
            ticker = stock.ticker
            tickers.append(ticker)
            index = getdata.getIndexTicker(getdata.getData([ticker],
                                getdata.getParamDict('stock exchange')))
            if index not in tickers:
                tickers.append(index)
		return getdata.get_history(tickers,start_date)
Beispiel #3
0
 def getHistory(self, start_date):
     tickers = []
     for stock in self.stocks:
         ticker = stock.ticker
         tickers.append(ticker)
         index = getdata.getIndexTicker(
             getdata.getData([ticker],
                             getdata.getParamDict('stock exchange')))
         if index not in tickers:
             tickers.append(index)
             return getdata.get_history(tickers, start_date)
Beispiel #4
0
 def updateSharesOwned(self, end_date):
     try:
         latest_transaction_date = max(
             [t['Date'] for t in self.transactions])
     except ValueError:
         latest_transaction_date = dt.today().date()
     dividends = getdata.get_dividend_history(
         self.ticker, latest_transaction_date - relativedelta(days=7),
         end_date)
     dividends['Date'] = dividends.index
     dividends.apply(lambda row: self.addTransaction(
         row['Dividends'], 'D',
         int(row['Dividends'] * self.shares_owned / (getdata.get_history(
             [self.ticker], (row['Date'] + pd.DateOffset(days=2)),
             (row['Date'] + pd.DateOffset(days=7)))[-1:]['Close'].values[0])
             ), row['Date'] + pd.DateOffset(days=7)),
                     axis=1)
     return
Beispiel #5
0
def construct_ranking_table(portfolio,lookbackDays=None,oldTable=None,enddate=dt.today().date(),index=None,silent=False):
#One,only one and exactly one of lookbackDays and oldTable should be specified.
  dfarr = []
  for stock in portfolio.stocks:
    if index == None:
      idx = getdata.getIndexTicker(getdata.getData([stock.ticker],getdata.getParamDict('stock exchange')))
    else:
      idx = index
	
    indexCurrVal = getdata.get_history([idx],
                                          dt.today()-relativedelta(days=5))[-1:]['Close'].values[0]
    try:
      indexPrevVal = getdata.get_history([idx],
										oldTable.ix[stock.ticker]['Date'])['Close'].values[0]
    except:
      indexPrevVal = getdata.get_history([idx],
                                          dt.today()-relativedelta(days=lookbackDays))['Close'].values[0]
    dftemp = pd.DataFrame(data=[0],index=[0])
	
    dftemp['Symbol'] = stock.ticker
    dftemp['Name'] = getdata.getData([stock.ticker],"n")
    dftemp['Price'] = getdata.get_history([stock.ticker],
                                          enddate-relativedelta(days=5))[-1:]['Close'].values[0]
    dftemp['Number Owned'] = stock.getSharesOwned()
    dftemp['Current Value'] = dftemp['Price']*dftemp['Number Owned']
#    try:
#      dftemp['Previous Value'] = oldTable.ix[stock.ticker]['Current Value']
#    except:
#        prev_number_owned = dftemp['Number Owned']
#        for transaction in stock.transactions:
#            if transaction['Date'] > (enddate-relativedelta(days=lookbackDays)):
#                if transaction['Type'] == 'Bought':
#                    prev_number_owned = prev_number_owned - transaction['Number']
#                elif transaction['Type'] == 'Sold':
#                    prev_number_owned = prev_number_owned + transaction['Number']
#        dftemp['Previous Value'] = prev_number_owned*getdata.get_history([stock.ticker],
#                                          enddate-relativedelta(days=lookbackDays))['Close'].values[0]
#    dftemp['%Gain (Period)'] = 100*(dftemp['Current Value'] - dftemp['Previous Value'])/dftemp['Previous Value']
    prev_adj_close = getdata.get_history([stock.ticker],
                                         enddate-relativedelta(days=lookbackDays))['Adj Close'].values[0]
    dftemp['%Gain (Period)'] = 100*((getdata.get_history([stock.ticker],
                                                        enddate-relativedelta(days=5))[-1:]['Adj Close'].values[0]
                                    - prev_adj_close)/prev_adj_close)
    dftemp['%Gain Index (Period)'] = 100*(indexCurrVal - indexPrevVal)/indexPrevVal
    dftemp['Index'] = idx
    dftemp['GainSt - GainIdx'] = dftemp['%Gain (Period)'] - dftemp['%Gain Index (Period)']
    #if dftemp['%Gain Index (Period)'] > dftemp['%Gain (Period)']:
    #  dftemp['Stock > Index'] = 'N'
    #else:
    #  dftemp['Stock > Index'] = 'Y'
    dftemp['Total Investment'] = stock.investment
    dftemp['%Total Gain'] = 100*(dftemp['Current Value'] - stock.investment)/stock.investment
    dftemp = dftemp.drop(0,axis=1)
    dftemp.index = dftemp['Symbol']
    dftemp = dftemp.drop('Symbol',axis=1)
    dfarr.append(dftemp)
  dftoret = pd.concat(dfarr)
  #dftoret = dftoret.sort(columns='Stock > Index',ascending=False)
  dftoret = dftoret.sort(columns='GainSt - GainIdx',ascending=False)
  dftoret = dftoret.drop('GainSt - GainIdx',axis=1)
  dftoret['Rank'] = range(1,len(dftoret)+1)
  dftoret['Date'] = np.repeat(enddate,dftoret.shape[0])
  if not silent:
    print "Stocks doing better than the market:",dftoret[dftoret['%Gain (Period)']>dftoret['%Gain Index (Period)']].index.values
    print "Stocks doing worse than the market:",dftoret[dftoret['%Gain (Period)']<dftoret['%Gain Index (Period)']].index.values[::-1]
  return dftoret
Beispiel #6
0
 def getHistory(self, start_date):
     return getdata.get_history([self.ticker], start_date)
Beispiel #7
0
 def updateSharesOwned(self,end_date):
     try:
         latest_transaction_date =  max([t['Date'] for t in self.transactions])
     except ValueError:
         latest_transaction_date = dt.today().date()
     dividends = getdata.get_dividend_history(self.ticker,latest_transaction_date-relativedelta(days=7),end_date)
     dividends['Date'] = dividends.index
     dividends.apply(lambda row: self.addTransaction(row['Dividends'],'D',
                                                     int(row['Dividends']*self.shares_owned/(getdata.get_history([self.ticker],
                                                                                                                 (row['Date']+pd.DateOffset(days=2)),
                                                                                                                 (row['Date']+pd.DateOffset(days=7)))
                                                                                                                 [-1:]['Close'].values[0])),
                                                     row['Date']+pd.DateOffset(days=7)),axis=1)
     return
Beispiel #8
0
	def getHistory(self,start_date):
		return getdata.get_history([self.ticker],start_date)
Beispiel #9
0
def construct_ranking_table(portfolio,
                            lookbackDays=None,
                            oldTable=None,
                            enddate=dt.today().date(),
                            index=None,
                            silent=False):
    #One,only one and exactly one of lookbackDays and oldTable should be specified.
    dfarr = []
    for stock in portfolio.stocks:
        if index == None:
            idx = getdata.getIndexTicker(
                getdata.getData([stock.ticker],
                                getdata.getParamDict('stock exchange')))
        else:
            idx = index

        indexCurrVal = getdata.get_history(
            [idx],
            dt.today() - relativedelta(days=5))[-1:]['Close'].values[0]
        try:
            indexPrevVal = getdata.get_history(
                [idx], oldTable.ix[stock.ticker]['Date'])['Close'].values[0]
        except:
            indexPrevVal = getdata.get_history(
                [idx],
                dt.today() -
                relativedelta(days=lookbackDays))['Close'].values[0]
        dftemp = pd.DataFrame(data=[0], index=[0])

        dftemp['Symbol'] = stock.ticker
        dftemp['Name'] = getdata.getData([stock.ticker], "n")
        dftemp['Price'] = getdata.get_history(
            [stock.ticker],
            enddate - relativedelta(days=5))[-1:]['Close'].values[0]
        dftemp['Number Owned'] = stock.getSharesOwned()
        dftemp['Current Value'] = dftemp['Price'] * dftemp['Number Owned']
        #    try:
        #      dftemp['Previous Value'] = oldTable.ix[stock.ticker]['Current Value']
        #    except:
        #        prev_number_owned = dftemp['Number Owned']
        #        for transaction in stock.transactions:
        #            if transaction['Date'] > (enddate-relativedelta(days=lookbackDays)):
        #                if transaction['Type'] == 'Bought':
        #                    prev_number_owned = prev_number_owned - transaction['Number']
        #                elif transaction['Type'] == 'Sold':
        #                    prev_number_owned = prev_number_owned + transaction['Number']
        #        dftemp['Previous Value'] = prev_number_owned*getdata.get_history([stock.ticker],
        #                                          enddate-relativedelta(days=lookbackDays))['Close'].values[0]
        #    dftemp['%Gain (Period)'] = 100*(dftemp['Current Value'] - dftemp['Previous Value'])/dftemp['Previous Value']
        prev_adj_close = getdata.get_history(
            [stock.ticker],
            enddate - relativedelta(days=lookbackDays))['Adj Close'].values[0]
        dftemp['%Gain (Period)'] = 100 * (
            (getdata.get_history([stock.ticker], enddate - relativedelta(
                days=5))[-1:]['Adj Close'].values[0] - prev_adj_close) /
            prev_adj_close)
        dftemp['%Gain Index (Period)'] = 100 * (indexCurrVal -
                                                indexPrevVal) / indexPrevVal
        dftemp['Index'] = idx
        dftemp['GainSt - GainIdx'] = dftemp['%Gain (Period)'] - dftemp[
            '%Gain Index (Period)']
        #if dftemp['%Gain Index (Period)'] > dftemp['%Gain (Period)']:
        #  dftemp['Stock > Index'] = 'N'
        #else:
        #  dftemp['Stock > Index'] = 'Y'
        dftemp['Total Investment'] = stock.investment
        dftemp['%Total Gain'] = 100 * (dftemp['Current Value'] -
                                       stock.investment) / stock.investment
        dftemp = dftemp.drop(0, axis=1)
        dftemp.index = dftemp['Symbol']
        dftemp = dftemp.drop('Symbol', axis=1)
        dfarr.append(dftemp)
    dftoret = pd.concat(dfarr)
    #dftoret = dftoret.sort(columns='Stock > Index',ascending=False)
    dftoret = dftoret.sort(columns='GainSt - GainIdx', ascending=False)
    dftoret = dftoret.drop('GainSt - GainIdx', axis=1)
    dftoret['Rank'] = range(1, len(dftoret) + 1)
    dftoret['Date'] = np.repeat(enddate, dftoret.shape[0])
    if not silent:
        print "Stocks doing better than the market:", dftoret[
            dftoret['%Gain (Period)'] >
            dftoret['%Gain Index (Period)']].index.values
        print "Stocks doing worse than the market:", dftoret[
            dftoret['%Gain (Period)'] <
            dftoret['%Gain Index (Period)']].index.values[::-1]
    return dftoret