Esempio n. 1
0
    def __init__(
            self,
            symbol,
            startdate_string='2004-12-31',
            enddate_string='',
            period='monthly'  #or daily
        ,
            source='Yahoo'
        #, enddate_string='xxx'
    ):
        print('Initialized class pullreturns.perform')

        #today_date = datetime.date.today()

        self.Symbol = symbol
        self.StartDateString = startdate_string
        self.EndDateString = enddate_string
        self.Period = period

        import datetime
        #today_datetime = datetime.datetime.today()

        startdate_date = datetime.datetime.strptime(startdate_string,
                                                    "%Y-%m-%d")
        my_enddate_string = enddate_string
        yesterday_date = datetime.date.fromordinal(
            datetime.date.today().toordinal() - 1)
        if len(my_enddate_string) == 0:
            my_enddate_string = str(yesterday_date)

        enddate_date = datetime.datetime.strptime(my_enddate_string,
                                                  "%Y-%m-%d")

        if enddate_date <= startdate_date:
            my_enddate_string = str(yesterday_date)

        import pullprices as pp
        if period == 'monthly':
            self._StockHistoryDataframe = pp.stockhistorybackfilledtodatframeofstockhistoryinstancesusingcache(
                symbol, startdate_string,
                my_enddate_string)  #,str(today_date))
            #self.MonthDayCharacter = 'M'
        else:
            self._StockHistoryDataframe = pp.stockhistorynobackfilltodataframeusingcache(
                symbol, startdate_string,
                my_enddate_string)  #,str(today_date))
            #self.MonthDayCharacter = 'D'

        #Append todays price if no end date specified
        appendtodaysprice = False
        if enddate_string == '':
            appendtodaysprice = True

        self.ReturnsDataframe = self.calculatereturns(
            period=period, appendtodaysprice=appendtodaysprice)

        self.PriceHistoryDataframe = self.getpricehistory(
            period=period, appendtodaysprice=appendtodaysprice)
        self.FirstDateOfPriceHistory = self.PriceHistoryDataframe.index.tolist(
        )[0]
    def __init__(
            self,
            symbol,
            startdate_string='2004-12-31'
        #, period = 'monthly' #or daily
        ,
            source='Yahoo'
        #, enddate_string='xxx'
    ):
        print('Initialized class pullreturns.perform')

        self.Symbol = symbol
        self.StartDateString = startdate_string
        #self.Period = period

        import datetime
        #today_datetime = datetime.datetime.today()
        #today_date = datetime.date.today()
        yesterday_date = datetime.date.fromordinal(
            datetime.date.today().toordinal() - 1)

        import pullprices as pp
        self.StockHistoryDataframe = pp.stockhistorybackfilledtodatframeofstockhistoryinstancesusingcache(
            symbol, startdate_string, str(yesterday_date))  #,str(today_date))
        self.ReturnsDataframe = self.monthlyreturns()
Esempio n. 3
0
    def __init__(
            self,
            symbol,
            startdate_string='2004-12-31',
            period='monthly'  #or daily
        ,
            source='Yahoo'
        #, enddate_string='xxx'
    ):
        print('Initialized class pullreturns.perform')

        self.Symbol = symbol
        self.StartDateString = startdate_string
        self.Period = period

        import datetime
        #today_datetime = datetime.datetime.today()
        #today_date = datetime.date.today()
        yesterday_date = datetime.date.fromordinal(
            datetime.date.today().toordinal() - 1)

        import pullprices as pp
        if period == 'monthly':
            self._StockHistoryDataframe = pp.stockhistorybackfilledtodatframeofstockhistoryinstancesusingcache(
                symbol, startdate_string,
                str(yesterday_date))  #,str(today_date))
            #self.MonthDayCharacter = 'M'
        else:
            self._StockHistoryDataframe = pp.stockhistorynobackfilltodataframeusingcache(
                symbol, startdate_string,
                str(yesterday_date))  #,str(today_date))
            #self.MonthDayCharacter = 'D'

        self.ReturnsDataframe = self.calculatereturns(period)
        self.PriceHistoryDataframe = self.getpricehistory(period)
 def _monthlyreturnsusingyahoosymbol(self,):
     # Parameters
     #startdate_string = '2004-12-31'
     #symbol = '^GSPC   ^OEX    ^VIX    ^OEX    ^MID   ^RUT
     symbol = self.Symbol 
     startdate_string = self.StartDateString
     # ##########
     # Date setup
     import datetime
     #today_datetime = datetime.datetime.today()
     today_date = datetime.date.today()
     yesterday_date = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
     #print str(today_date)
     
     import pullprices as pp
     df_00 = pp.stockhistorybackfilledtodatframeofstockhistoryinstancesusingcache(symbol,startdate_string,str(yesterday_date)) #,str(today_date))
     #print list(df_00)#['Close','Adj Close']
     #print df_00[['Close','Adj Close']]
     
     import pandas as pd
     dates1 = pd.date_range('1910-01', str(today_date)[:7], freq='M')
     
     dummy_date = datetime.datetime.strptime("1801-01-01", "%Y-%m-%d")
     prev_date = dummy_date
     prev_value = float('Nan')
     
     rows_monthlyreturns = []        
     #rows_optionpricescurrent.append(['optionsymbol','stockprice','strike','pdeltapct_to_sell_price','cumprob_to_sell_price','bid','ask','last'])
     rows_monthlyreturns.append(['a_symbol','b_monthend','e_pctchange','d_end'])
     
     
     for dt in dates1:
         if str(dt.date()) in df_00.index:
             #print dt.date()
             myobj = df_00.loc[str(dt.date())]
             #print myobj
             curr_date = dt.date()
             curr_value = myobj['Adj Close']
             if prev_date != dummy_date:
                 #print 'pullreturns curr_value,prev_value',curr_value,prev_value
                 if is_number(curr_value) and is_number(prev_value):
                     change_pct = (float(curr_value) - float(prev_value))/float(prev_value)
                 else:
                     change_pct =  float('NaN')
                 
                 #print symbol,prev_date,prev_value,curr_date,curr_value,change_pct
                 rows_monthlyreturns.append([symbol,curr_date,change_pct,curr_value])
                 #'{percent:.2%}'.format(percent=pdeltapct_to_sell_price)
                 #print symbol,curr_date,change_pct
                 
             prev_date = dt.date()
             prev_value = myobj['Adj Close']
     
     
     headers = rows_monthlyreturns.pop(0)
     df_monthlyreturns = pd.DataFrame(rows_monthlyreturns,columns=headers)
     import numpy as np
     df_monthlyreturnsfinite = df_monthlyreturns[np.isfinite(df_monthlyreturns['e_pctchange'])]
     #print df_monthlyreturnsfinite
     #print df_00
     
     stock_dataframe = pp.stock_dataframe(symbol)
     myobj = df_00.loc[str(prev_date)]
     prev_ending = myobj['Adj Close']
     curr_price = stock_dataframe['last'][0]
     if is_number(curr_price) and is_number(prev_ending):
         curr_pctchange = (float(curr_price) - float(prev_ending)) / float(prev_ending)
     else:
         curr_pctchange = float('NaN')
     
     #df_curr = pd.DataFrame([symbol,today_date,curr_pctchange], columns=['a_symbol','b_monthend','e_pctchange'])
     #newrow = np.array([symbol,today_date,curr_pctchange])
     #columns=['a_symbol','b_monthend','e_pctchange','d_end']
     
     #import numpy as np
     
     mydict = {}
     mydict[0] = {'a_symbol':symbol,'b_monthend':str(today_date),'e_pctchange':curr_pctchange,'d_end':curr_price}
     df_curr = pd.DataFrame(mydict).T
     #print df_curr.T
     
     
     df_monthlyreturnstotoday = df_monthlyreturnsfinite.append(df_curr, ignore_index=True)
     #print df_monthlyreturns
     #print str(today_date)[:7]
     return df_monthlyreturnstotoday
# Parameters
startdate_string = '1980-01-01'
symbol = '^GSPC' #  ^GSPC   ^OEX    ^VIX    ^OEX    ^MID   ^RUT
# ##########
# Date setup
import datetime
today_datetime = datetime.datetime.today()
today_date = datetime.date.today()
yesterday_date = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
print str(today_date)

import pullprices as pp
df_00 = pp.stockhistorybackfilledtodatframeofstockhistoryinstancesusingcache(symbol,startdate_string,str(yesterday_date)) #,str(today_date))
#print list(df_00)#['Close','Adj Close']
#print df_00[['Close','Adj Close']]

import pandas as pd
dates1 = pd.date_range('1910-01', '2015-12', freq='M')

dummy_date = datetime.datetime.strptime("1801-01-01", "%Y-%m-%d")
prev_date = dummy_date
prev_value = float('Nan')

rows_monthlyreturns = []        
#rows_optionpricescurrent.append(['optionsymbol','stockprice','strike','pdeltapct_to_sell_price','cumprob_to_sell_price','bid','ask','last'])
rows_monthlyreturns.append(['a_symbol','b_monthend','e_pctchange','d_end '])


for dt in dates1:
    if str(dt.date()) in df_00.index:
        #print dt.date()
Esempio n. 6
0
import pullprices as pp
df1 = pp.stockhistorybackfilledtodatframeofstockhistoryinstancesusingcache('FB','2011-01-01','2015-07-17')
df2 = df1.dropna(subset=['Open'])
print df2

Esempio n. 7
0
import pullprices as pp
df1 = pp.stockhistorybackfilledtodatframeofstockhistoryinstancesusingcache(
    'FB', '2011-01-01', '2015-07-17')
df2 = df1.dropna(subset=['Open'])
print df2
Esempio n. 8
0
    def build(self, symbol, param_numberofweeks, daysbackmid, daysbackfar,
              showresults):

        import pandas as pd
        import numpy as np

        if showresults == 1:
            print('mysymbol', symbol, '------------------------------------')

        #param_numberofweeks = 4
        numberofweekstorun = param_numberofweeks

        from datetime import datetime, timedelta
        dStart = datetime.now().date() + timedelta(weeks=-numberofweekstorun)
        #print(dStart)

        index = pd.date_range(dStart + timedelta(days=0),
                              periods=numberofweekstorun,
                              freq='W-Fri')
        #print(index)
        columns = [
            'dateDaysBackMid', 'dateDaysBackFar', 'priceRefDate',
            'priceDaysBackMid', 'priceDaysBackFar', 'DeltaFartoMid',
            'DrawDownMax', 'DrawUpMax', 'DrawDownPctChange', 'DrawUpPctChange'
        ]
        df_ = pd.DataFrame(index=index, columns=columns)
        df_ = df_.fillna(0)  # with 0s rather than NaNs
        #df_ = df_.fillna(method='pad')

        # ------------------------------------------------------------
        # Change this number after * if changing the number of columns
        data = np.array([np.arange(len(index))] * 10).T
        # ------------------------------------------------------------

        df = pd.DataFrame(data, index=index, columns=columns)
        #-------------------------------------------------------------------------------

        import pullprices
        fmt = '%Y-%m-%d'

        dEnd = index[-1]
        dEnd_string = dEnd.strftime(fmt)

        dDataStart = dStart + timedelta(days=(-1 * daysbackfar) - 1)
        dDataStart_string = dDataStart.strftime(fmt)
        #f = pullprices.stockhistory(symbol, dDataStart, dEnd)
        df_backfilled = pullprices.stockhistorybackfilledtodatframeofstockhistoryinstancesusingcache(
            symbol, dDataStart_string, dEnd_string)
        #df_backfilled_nonan = df_backfilled.dropna(subset=['Open'])
        #print(f)
        for idx, row in df.iterrows():
            pDraw_downmax = 0
            pDraw_upmax = 0
            #print(idx)
            dRef = idx
            ddaysbackmid = dRef + timedelta(days=-1 * daysbackmid)
            ddaysbackfar = dRef + timedelta(days=-1 * daysbackfar)

            dRef_string = dRef.strftime(fmt)
            ddaysbackmid_string = ddaysbackmid.strftime(fmt)
            ddaysbackfar_string = ddaysbackfar.strftime(fmt)

            try:
                pdaysbackfar = df_backfilled.ix[ddaysbackfar_string][
                    'Adj Close']
                #print(ddaysbackfar_string,pdaysbackfar)

            except:
                pdaysbackfar = float('NaN')
                #print('no data')
                pass
            try:
                pdaysbackmid = df_backfilled.ix[ddaysbackmid_string][
                    'Adj Close']
                #print(ddaysbackmid_string,pdaysbackmid)
            except:
                pdaysbackmid = float('NaN')
                #print('no data')
                pass
            try:
                pRef = df_backfilled.ix[dRef_string]['Adj Close']
                #print(dRef_string,pRef)
            except:
                pRef = float('NaN')
                #print('no data')
                pass
            try:
                pdeltadaysbackfartodaysbackmid = pdaysbackmid - pdaysbackfar
                #print('pricedelta',pdeltadaysbackfartodaysbackmid)
            except:
                pdeltadaysbackfartodaysbackmid = float('NaN')
                #print('no delta')

            for iday in range(1, daysbackfar - daysbackmid + 1):
                dDraw = ddaysbackfar + timedelta(days=iday)
                dDraw_string = dDraw.strftime(fmt)
                #print(dDraw_string)
                try:
                    pDraw = df_backfilled.ix[dDraw_string]['Adj Close']

                    pDelta = pDraw - pdaysbackfar

                    if pDelta < pDraw_downmax:
                        pDraw_downmax = pDelta
                    if pDelta > pDraw_upmax:
                        pDraw_upmax = pDelta
                    if pdaysbackfar == float('NaN'):
                        pDraw_downmax = float('NaN')
                        pDraw_upmax = float('NaN')
                except:
                    pDraw = float('Nan')
            #print(dRef_string,ddaysbackmid_string,ddaysbackfar_string)
            #print('inside builddataframeofrefdateminusd2tod1stockpricechanges.py','WAWAWAWAWAW pDraw_downmax,pdaysbackfar',pDraw_downmax,pdaysbackfar)

            try:
                pctchangeDraw_downmax = pDraw_downmax / pdaysbackfar
            except:
                pctchangeDraw_downmax = float('NaN')

            try:
                pctchangeDraw_upmax = pDraw_upmax / pdaysbackfar
            except:
                pctchangeDraw_upmax = float('NaN')

            df.loc[dRef] = pd.Series({
                'dateDaysBackMid':
                ddaysbackmid.strftime('%Y-%m-%d'),
                'dateDaysBackFar':
                ddaysbackfar.strftime('%Y-%m-%d'),
                'priceRefDate':
                pRef,
                'priceDaysBackMid':
                pdaysbackmid,
                'priceDaysBackFar':
                pdaysbackfar,
                'DeltaFartoMid':
                pdeltadaysbackfartodaysbackmid,
                'DrawDownMax':
                pDraw_downmax,
                'DrawUpMax':
                pDraw_upmax,
                'DrawDownPctChange':
                abs(pctchangeDraw_downmax),
                'DrawUpPctChange':
                pctchangeDraw_upmax
            })
            #print('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')

        #df = df.fillna(method='pad')

        if showresults == 1:
            print(df)
            print(len(data))
            print(len(df))

            print('------------------------')
            print(dStart)
            print(dEnd)
            print('dRef', dRef)
        self.DataFrameResult = df