Пример #1
0
def calc_sharpe_ratio_sym(data,
                          symbol,
                          lookbackDays,
                          enddate=dt.today(),
                          index=None,
                          silent=False):
    #data: Dataframe containing at least date for the required time period for the required symbol and index
    #symbol: Symbol for which sharpe ratio is to be calculated
    #lookbackDays: # of days to look back from the enddate to calculate sharpe ratio
    #enddate: Last day for sharpe ratio calculation
    #index: Reference index to be used
    #silent: silence print statements
    if index == None:
        index = getdata.getIndexTicker(
            getdata.getData([symbol], getdata.getParamDict('stock exchange')))
    #data = getdata.get_history([symbol,index],dt.today()-relativedelta(days=days))
    #data = data.drop(['Open','High','Low','Close','Volume'],axis=1)
    #data = data.unstack(0).swaplevel(0,1,axis=1).sortlevel(0,axis=1)
    data = append_return(data)
    r_sym = data.ix[symbol]['return'].ix[(
        enddate - relativedelta(days=lookbackDays)):enddate]
    r_index = data.ix[index]['return'].ix[(
        enddate - relativedelta(days=lookbackDays)):enddate]
    r_sym_mean = r_sym.mean()
    r_index_mean = r_index.mean()
    std_sym_wrt_index = (r_sym - r_index).std()
    answer = (r_sym_mean - r_index_mean) / std_sym_wrt_index
    if not silent:
        print days, "day Sharpe Ratio for", symbol, "=", answer
    return answer
Пример #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)
Пример #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)
Пример #4
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
Пример #5
0
def calc_sharpe_ratio_sym(data,symbol,lookbackDays,enddate=dt.today(),index=None,silent=False):
  #data: Dataframe containing at least date for the required time period for the required symbol and index
  #symbol: Symbol for which sharpe ratio is to be calculated
  #lookbackDays: # of days to look back from the enddate to calculate sharpe ratio
  #enddate: Last day for sharpe ratio calculation
  #index: Reference index to be used
  #silent: silence print statements
  if index == None:
    index = getdata.getIndexTicker(getdata.getData([symbol],getdata.getParamDict('stock exchange')))
  #data = getdata.get_history([symbol,index],dt.today()-relativedelta(days=days))
  #data = data.drop(['Open','High','Low','Close','Volume'],axis=1)
  #data = data.unstack(0).swaplevel(0,1,axis=1).sortlevel(0,axis=1)
  data = append_return(data)
  r_sym = data.ix[symbol]['return'].ix[(enddate-relativedelta(days=lookbackDays)):enddate]
  r_index = data.ix[index]['return'].ix[(enddate-relativedelta(days=lookbackDays)):enddate]
  r_sym_mean = r_sym.mean()
  r_index_mean = r_index.mean()
  std_sym_wrt_index = (r_sym-r_index).std()
  answer = (r_sym_mean-r_index_mean)/std_sym_wrt_index
  if not silent:
    print days, "day Sharpe Ratio for",symbol, "=",answer
  return answer
Пример #6
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
Пример #7
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