Esempio n. 1
0
def driptest(numlist):
    '''
    input: a list of numbers (nums corrsp to stocks listed in tckrlist)
    output: the value of a portfolio containing stocks specified  in numlist starting on 9/19/2000 and ending on 7/15/2013
            divs reinvested at price on close of pay dates
    '''
    #TODO add semi-annual contributions, invested evenly between all stocks, every 130 days
    cashperstock = 50000/len(numlist) #start with $50,000 dollars divided by number of stocks
    holdingslist = []

    for i in numlist: #buy initial shares
        price = mf.parse_yahoo_historical(mf.fetch_historical_yahoo(tckrlist[i], (2000, 9, 19), (2000, 9, 19), dividends=False), adjusted=False)
        iprice = price[0][2]

        ishares = round(cashperstock/iprice, 2)
        holdingslist.append(ishares)

    for i in fulldatelist: #for every day in window
        hcount = 0
        p = i.split('/')
        d = int(p[1])
        yahoodate = (int(p[2]), int(p[0]), d) # a yahoo fetch compatible date
        hcount = 0
        for j in numlist: #look at every stock in the numlist
            paycount = 0
            icurrprice = 0
            d = int(p[1])
            yahoodate = (int(p[2]), int(p[0]), d)
            for k in paydatemaster[j]: #for each stock, look at payment date master list
                k = k.strip()
                if k == i: #check if current day is a dividend pay day
                    paymentmaster[j][paycount] = float(paymentmaster[j][paycount])
                    divpaymt = round(paymentmaster[j][paycount]*holdingslist[hcount], 2)

                    try:
                        currprice = mf.parse_yahoo_historical(mf.fetch_historical_yahoo(tckrlist[j], yahoodate, yahoodate, dividends=False), adjusted=False)
                        icurrprice = currprice[0][2]
                        holdingslist[hcount] += round(divpaymt/icurrprice, 3) #reinvest, using yahoo data, tckrlist[j]
                    except: #sometimes paydates are on the weekend, in which case the next available day's close price is used     
                        while icurrprice == 0:
                            d+= 1
                            try:
                                yahoodate = (int(p[2]), int(p[0]), d)
                                currprice = mf.parse_yahoo_historical(mf.fetch_historical_yahoo(tckrlist[j], yahoodate, yahoodate, dividends=False), adjusted=False)
                                icurrprice = currprice[0][2]
                                holdingslist[hcount] += round(divpaymt/icurrprice, 3)
                            except:
                                pass
                paycount += 1
            hcount += 1

    finaldate = (2013, 7, 15)
    count = 0
    value = 0
    for i in numlist:
        finalprice = mf.parse_yahoo_historical(mf.fetch_historical_yahoo(tckrlist[i], finaldate, finaldate, dividends=False), adjusted=False)
        ifinalprice = finalprice[0][2]
        value += round(ifinalprice*holdingslist[count], 2) #calculate final value
        count += 1
    return value
Esempio n. 2
0
def manualtest(numlist):
    '''
    input: a list of numbers (nums corrsp to stocks listed in tckrlist)
    output: the value of a portfolio containing stocks specified in numlist starting on 9/19/2000 and ending on 7/15/2013
            using a manual reinvestment strategy
    '''
    daycount = 0
    cash = 0
    transactions = 0
    cashperstock = 50000/len(numlist) #start with $50,000 dollars divided by number of stocks
    holdingslist = []

    for i in numlist: #buy initial shares

        price = mf.parse_yahoo_historical(mf.fetch_historical_yahoo(tckrlist[i], (2000, 9, 19), (2000, 9, 19), dividends=False), adjusted=False)
        iprice = price[0][2]

        ishares = round(cashperstock/iprice, 2)
        holdingslist.append(ishares)

    for i in fulldatelist: #for every day in window
        fiftydaylist = []
        buyconditiontf =[]
        tendaylist= []
        mrdaystckprice = []

        hcount = 0
        for j in numlist: #look at every stock in the randomly chosen numlist
            paycount = 0
            for k in paydatemaster[j]: #for each stock, look at payment date master list
                k = k.strip()
                if k == i: #check if current day is a div pay day
                    paymentmaster[j][paycount] = float(paymentmaster[j][paycount])
                    divpaymt = round(paymentmaster[j][paycount]*holdingslist[hcount], 2)
                    cash += divpaymt # if it's a pay day, add the div payment to cash
                paycount += 1
            hcount += 1  

        if daycount > 50: # if more than 50 days have passed
            for u in numlist:
                tempolist = []
                dcount = 0
                for p in stockdatemaster[u]:
                    if p == i:
                        tempolist = stockpricemaster[u][dcount:dcount+50] #stock prices for last 50 days
                    dcount += 1
                if len(tempolist) != 0:
                    fstdv, favg = meanstdv(tempolist) #calculate fifty day moving average
                    tstdv, tavg = meanstdv(tempolist[:10]) #calculate 10 day moving average
                    fiftydaylist.append(favg)
                    tendaylist.append(tavg)
                    mrdaystckprice.append(tempolist[0])

        fcount = 0
        truelist = [] 

        for s in mrdaystckprice:
            
            if float(s) < fiftydaylist[fcount] and float(s) < tendaylist[fcount] and tendaylist[fcount] < fiftydaylist[fcount]: #buy criteria defined
                buyconditiontf.append(True)
                truelist.append(fcount)
#                print i
                
            else:
                buyconditiontf.append(False)
            
            fcount += 1
        fcount = 0

        if cash != 0 and len(truelist) != 0: #if there is cash available and one or more buy criteria have been met
            if cash/len(truelist) > 500: #if there's more than $500 cash
                for e in buyconditiontf: 
                    if e == True:

                        holdingslist[fcount] += (cash/len(truelist))/float(mrdaystckprice[fcount]) #for all stocks meeting buy criteria, add to holdings using available cash
                        transactions += 1 #add one transaction to the list
                    fcount += 1
                cash = 0 #reset cash to zero; all cash was spent adding to stocks meeting buy criteria

        daycount += 1
    finaldate = (2013, 7, 15)
    count = 0
    value = 0
    for i in numlist:
        finalprice = mf.parse_yahoo_historical(mf.fetch_historical_yahoo(tckrlist[i], finaldate, finaldate, dividends=False), adjusted=False)
        ifinalprice = finalprice[0][2]

        value += round((ifinalprice*holdingslist[count])+cash, 2) #calculate final value for each stock
        count += 1
        
    return value, transactions
Esempio n. 3
0
import matplotlib.pyplot as plt
import matplotlib.finance as f
import numpy as np

spy = f.fetch_historical_yahoo('SPY', (2007,1,1), (2008,12,31))
agg = f.fetch_historical_yahoo('AGG', (2007,1,1,), (2008,12,31))

spy_l = f.parse_yahoo_historical(spy, adjusted=True, asobject=False)
agg_l = f.parse_yahoo_historical(agg, adjusted=True, asobject=False)
print spy_l
print agg_l

ndays = min(len(spy_l),len(agg_l)) - 1
print 'ndays', ndays

spy_daily = []
agg_daily = []
for i in range(1, ndays):
    spy_daily.append(float(spy_l[i][4]) / float(spy_l[i+1][4]) - 1)
    agg_daily.append(float(agg_l[i][4]) / float(agg_l[i+1][4]) - 1)
print spy_daily    
print agg_daily

x = np.array(spy_daily, dtype='float')
y = np.array(agg_daily, dtype='float')

plt.axis('equal')
plt.grid(True)
plt.xlabel('spy')
plt.ylabel('agg')
plt.title('daily returns during financial crisis')