Exemplo n.º 1
0
def getAllStockData(ticker):
    '''Get a few random tickers.'''
    stock = Share(ticker)
    stock.refresh()
    data = {
        'name': stock.get_name(),
        'price': stock.get_price(),
        'change': stock.get_change(),
        'volume': stock.get_volume(),
        'prev_close': stock.get_prev_close(),
        'open': stock.get_open(),
        'avg_daily_volume': stock.get_avg_daily_volume(),
        'stock_exchange': stock.get_stock_exchange,
        'market_cap': stock.get_market_cap(),
        'book_value': stock.get_book_value(),
        'ebitda': stock.get_ebitda(),
        'dividend_share': stock.get_dividend_share(),
        'dividend_yield': stock.get_dividend_yield(),
        'earnings_share': stock.get_earnings_share(),
        'days_high': stock.get_days_high(),
        'days_low': stock.get_days_low(),
        'year_high': stock.get_year_high(),
        'year_low': stock.get_year_low(),
        '50day_moving_avg': stock.get_50day_moving_avg(),
        '200day_moving_avg': stock.get_200day_moving_avg(),
        'price_earnings_ratio': stock.get_price_earnings_ratio(),
        'price_earnings_growth_ratio': stock.get_price_earnings_growth_ratio(),
        'get_price_sales': stock.get_price_sales(),
        'get_price_book': stock.get_price_book(),
        'get_short_ratio': stock.get_short_ratio(),
        'trade_datetime': stock.get_trade_datetime(),
        'percent_change_from_year_high': stock.get_percent_change_from_year_high(),
        'percent_change_from_year_low': stock.get_percent_change_from_year_low(),
        'change_from_year_low': stock.get_change_from_year_low(),
        'change_from_year_high': stock.get_change_from_year_high(),
        'percent_change_from_200_day_moving_average': stock.get_percent_change_from_200_day_moving_average(),
        'change_from_200_day_moving_average': stock.get_change_from_200_day_moving_average(),
        'percent_change_from_50_day_moving_average': stock.get_percent_change_from_50_day_moving_average(),
        'change_from_50_day_moving_average': stock.get_change_from_50_day_moving_average(),
        'EPS_estimate_next_quarter': stock.get_EPS_estimate_next_quarter(),
        'EPS_estimate_next_year': stock.get_EPS_estimate_next_year(),
        'ex_dividend_date': stock.get_ex_dividend_date(),
        'EPS_estimate_current_year': stock.get_EPS_estimate_current_year(),
        'price_EPS_estimate_next_year': stock.get_price_EPS_estimate_next_year(),
        'price_EPS_estimate_current_year': stock.get_price_EPS_estimate_current_year(),
        'one_yr_target_price': stock.get_one_yr_target_price(),
        'change_percent_change': stock.get_change_percent_change(),
        'divended_pay_date': stock.get_dividend_pay_date(),
        'currency': stock.get_currency(),
        'last_trade_with_time': stock.get_last_trade_with_time(),
        'days_range': stock.get_days_range(),
        'years_range': stock.get_year_range()
    }
    return data
def checklist(symbol, ibd50_list, ibd_session):
    """
    Looks up information on a given stock market symbol.
    The returned dictionary contains all information from
    Dr. Wish's Stock Checklist for HONR348M.
    """
    stock = {}
    # Load price data from yahoo.
    share = Share(symbol)
    ks = yahoo_ks(symbol)

    # Basics
    basics = stock["basics"] = {}
    basics["date"] = datetime.now().strftime("%m/%d/%Y %I:%M:%S%z")
    basics["symbol"] = symbol
    basics["equity_name"] = share.get_name()
    basics["price"] = float(share.get_price())
    basics["52w_low"] = float(share.get_year_low())
    basics["52w_high"] = float(share.get_year_high())
    basics["percent_from_52w_low"] = share.get_percent_change_from_year_low()
    basics["percent_from_52w_high"] = share.get_percent_change_from_year_high()

    # IBD (Stocks only)
    ibd = stock["ibd"] = ibd_stock_checkup(symbol, ibd_session)
    # ibd["industry"]
    ibd["industry_rank"] = float(ibd["industry_rank"])
    # ibd["industry_top5"]
    # ibd["3y_eps_growth"]
    # ibd["3y_sales_growth"]
    # ibd["eps_change"]
    ibd["eps_rating"] = float(ibd["eps_rating"])
    ibd["rs_rating"] = float(ibd["rs_rating"])
    # ibd["acc_distr_rating"]
    ibd["ibd_rating"] = float(ibd["ibd_rating"])
    ibd["in_ibd50"] = symbol in ibd50_list
    # ibd["fundamental_greens"]
    # ibd["technical_greens"]
    ibd["next_earning"] = datetime.strptime(ibd["next_earning"], '%m/%d/%Y')

    # Yahoo Finance (Stocks only)
    yahoo = stock["yahoo"] = {}
    yahoo["pe"] = float(share.get_price_earnings_ratio())
    yahoo["peg"] = float(share.get_price_earnings_growth_ratio())
    yahoo["ps"] = float(share.get_price_sales())
    yahoo["market_cap"] = share.get_market_cap()
    yahoo["float"] = ks["Float"]
    yahoo["annual_roe"] = ks["Return on Equity"]
    yahoo["percent_inst"] = ks["% Held by Institutions"]
    yahoo["percent_float_short"] = ks["Short % of Float"]
    yahoo["short_ratio"] = float(share.get_short_ratio())

    # Evidence of an uptrend/downtrend
    uptrend = stock["uptrend"] = {}
    downtrend = stock["downtrend"] = {}

    pdstockdata = data.DataReader(symbol, 'yahoo', '1900-01-01')
    sd = StockDataFrame.retype(pdstockdata)
    sd.BOLL_PERIOD = 15

    close1 = sd['close'][-1]
    close2 = sd['close'][-2]
    low1 = sd['low'][-1]
    low2 = sd['low'][-2]
    high1 = sd['high'][-1]
    high2 = sd['high'][-2]
    avg_30d = sd['close_30_sma'][-1]
    avg_4w = sd['close_20_sma'][-1]
    avg_10w = sd['close_50_sma'][-1]
    avg_30w = sd['close_150_sma'][-1]
    high_52w = sd['high'].tail(250).max()
    lbb1 = sd['boll_lb'][-1]
    lbb2 = sd['boll_lb'][-2]
    ubb1 = sd['boll_ub'][-1]
    ubb2 = sd['boll_ub'][-2]

    # Find all GLTs (ATH not broken for at least another 90 days)
    last_ath = 0.0
    ath = Series()
    for day, day_high in sd['high'].iteritems():
        last_ath = max(last_ath, day_high)
        ath.set_value(day, last_ath)
    ath_days = sd[sd['high'] == ath]['high']
    glt = Series()
    for i, (day, high) in enumerate(ath_days.iteritems()):
        next_day = ath_days.keys()[i +
                                   1] if i < len(ath_days) - 1 else Timestamp(
                                       str(date.today()))
        if next_day - day >= Timedelta('90 days'):
            glt.set_value(day, high)

    uptrend["c>30d_avg"] = close1 > avg_30d
    uptrend["c>10w_avg"] = close1 > avg_10w
    uptrend["c>30w_avg"] = close1 > avg_30w
    uptrend["4w>10w>30w"] = avg_4w > avg_10w > avg_30w
    # uptrend["w_rwb"] =
    uptrend["last_glt_date"] = glt.keys()[-1].to_datetime().date(
    ) if len(glt) > 0 else None
    uptrend["last_glt_high"] = glt[-1] if len(glt) > 0 else None
    uptrend["above_last_glt"] = len(glt) > 0 and close1 > glt[-1]
    uptrend["macd_hist_rising"] = sd['macdh'][-1] > sd['macdh_4_sma'][-1]
    uptrend["stoch_fast>slow"] = sd['rsv_10_4_sma'][-1] > sd[
        'rsv_10_4_sma_4_sma'][-1]
    # uptrend["bb_up_expansion_l2"]
    # uptrend["rs>30d_avg"] = (Need Investors.com data)
    # uptrend["rs_rising"] = (Need Investors.com data)
    uptrend["52w_high_l2"] = high_52w == high1 or high_52w == high2
    uptrend["ath_l2"] = ath[-1] == high1 or ath[-2] == high2
    uptrend["1y_doubled"] = close1 >= 2 * sd['close'][-255:-245].mean()
    # uptrend["bounce_30d_l2"] =
    # uptrend["bounce_10w_l2"] =
    # uptrend["bounce_30w_l2"] =
    uptrend["stoch<50"] = sd['rsv_10_4_sma'][-1] < 50
    uptrend["<bb_lower_l2"] = low1 < lbb1 or low2 < lbb2
    uptrend[
        "above_avg_volume"] = sd['volume'][-1] > 1.5 * sd['volume_50_sma'][-1]

    downtrend["c<30d_avg"] = close1 < avg_30d
    downtrend["c<10w_avg"] = close1 < avg_10w
    downtrend["c<30w_avg"] = close1 < avg_30w
    downtrend["4w<10w<30w"] = avg_4w < avg_10w < avg_30w
    # downtrend["w_bwr"] =
    downtrend["macd_hist_falling"] = sd['macdh'][-1] < sd['macdh_4_sma'][-1]
    downtrend["stoch_fast<slow"] = sd['rsv_10_4_sma'][-1] < sd[
        'rsv_10_4_sma_4_sma'][-1]
    # downtrend["bb_down_expansion_l2"]
    # downtrend["bounce_30d_l2"] =
    # downtrend["bounce_10w_l2"] =
    # downtrend["bounce_30w_l2"] =
    downtrend["stoch>50"] = sd['rsv_10_4_sma'][-1] > 50
    downtrend[">bb_upper_l2"] = high1 > ubb1 or high2 > ubb2

    return stock
Exemplo n.º 3
0
print "get_year_high:", tesla.get_year_high()
print "get_year_low:", tesla.get_year_low()
print "get_50day_moving_avg:", tesla.get_50day_moving_avg()
print "get_200day_moving_avg:", tesla.get_200day_moving_avg()
print "get_price_earnings_ratio:", tesla.get_price_earnings_ratio()
print "get_price_earnings_growth_ratio:", tesla.get_price_earnings_growth_ratio(
)
print "get_price_sales:", tesla.get_price_sales()
print "get_price_book:", tesla.get_price_book()
print "get_short_ratio:", tesla.get_short_ratio()
print "get_trade_datetime:", tesla.get_trade_datetime()
# "a:", print tesla.get_historical(start_date, end_date)
# "a:", print tesla.get_info()
print "get_name:", tesla.get_name()
print "refresh:", tesla.refresh()
print "get_percent_change_from_year_high:", tesla.get_percent_change_from_year_high(
)
print "get_percent_change_from_year_low:", tesla.get_percent_change_from_year_low(
)
print "get_change_from_year_low:", tesla.get_change_from_year_low()
print "get_change_from_year_high:", tesla.get_change_from_year_high()
print "get_percent_change_from_200_day_moving_average:", tesla.get_percent_change_from_200_day_moving_average(
)
print "get_change_from_200_day_moving_average:", tesla.get_change_from_200_day_moving_average(
)
print "get_percent_change_from_50_day_moving_average:", tesla.get_percent_change_from_50_day_moving_average(
)
print "get_change_from_50_day_moving_average:", tesla.get_change_from_50_day_moving_average(
)
print "get_EPS_estimate_next_quarter:", tesla.get_EPS_estimate_next_quarter()
print "get_EPS_estimate_next_year:", tesla.get_EPS_estimate_next_year()
print "get_ex_dividend_date:", tesla.get_ex_dividend_date()
Exemplo n.º 4
0
def result_page(request):
    rstlist = list()
    grow_sortlst = list()
    value_sortlst = list()
    quality_sortlst = list()

    grow_stcklist = [ 'PNW','RL','PPG','ACN', 'ATVI', 'AYI', 'AMD', 'LNT', 'ALXN', 'GOOGL']
    value_stcklist = ['AMG', 'AFL', 'APD', 'AKAM','PCG','PM','PSX', 'AAP', 'AES', 'AET']
    quality_stcklist = ['MMM', 'ABT', 'ABBV','PEP','PKI','PRGO','PFE', 'ALB', 'ECL', 'AGN']
    stckdict = dict()

    if request.method == 'POST':
        allotment = int(str(request.POST['allotment']))
        ori_allotment = allotment
        iv_type = 0
        for key in request.POST.keys():
            print "iv_type="+str(iv_type)
            print str(key)
            if key in ['ethical','growth','index','quality','value']:
                iv_type = iv_type + 1

        print("current selected types count = " + str(iv_type))
        if iv_type == 2:
            allotment = allotment/float(2)

        if 'ethical' in request.POST.keys():
            AAPL = Share('AAPL')
            aapl_f = float(str(AAPL.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(AAPL.get_percent_change_from_50_day_moving_average())[0:-1]) - \
                     float(str(AAPL.get_percent_change_from_year_high())[0:-1])

            ADBE = Share('ADBE')
            adbe_f = float(str(ADBE.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(ADBE.get_percent_change_from_50_day_moving_average())[0:-1]) - \
                     float(str(ADBE.get_percent_change_from_year_high())[0:-1])

            NSRGY = Share('NSRGY')
            nsrgy_f = float(str(NSRGY.get_percent_change_from_year_low())[0:-1]) + \
                      float(str(NSRGY.get_percent_change_from_50_day_moving_average())[0:-1]) - \
                      float(str(NSRGY.get_percent_change_from_year_high())[0:-1])
            stckdict['AAPL'] = AAPL
            stckdict['ADBE'] = ADBE
            stckdict['NSRGY'] = NSRGY
            total_f = (aapl_f + adbe_f + nsrgy_f)*iv_type
            aapl_pct = aapl_f/float(total_f)
            adbe_pct = adbe_f/float(total_f)
            nsrgy_pct = nsrgy_f/float(total_f)
            aaplD = {"sticker":"AAPL","name":AAPL.get_name(),"aloc_pct":str(aapl_pct),"aloc_amt":str(allotment*aapl_pct),"price":str(AAPL.get_price()),"exchange":str(AAPL.get_stock_exchange())}
            adbeD = {"sticker":"ADBE","name":ADBE.get_name(),"aloc_pct":str(adbe_pct),"aloc_amt":str(allotment*adbe_pct),"price":str(ADBE.get_price()),"exchange":str(ADBE.get_stock_exchange())}
            nsrgyD = {"sticker":"NSRGY","name":NSRGY.get_name(),"aloc_pct":str(nsrgy_pct),"aloc_amt":str(allotment*nsrgy_pct),"price":str(NSRGY.get_price()),"exchange":str(NSRGY.get_stock_exchange())}
            rstlist.append(aaplD)
            rstlist.append(adbeD)
            rstlist.append(nsrgyD)

        if 'growth' in request.POST.keys():
            for stock in grow_stcklist:
                while True:
                    try:
                        detail = Share(stock)
                    except:
                        time.sleep(0.1)
                        continue
                    break
                stckdict[stock]=detail
                heapq.heappush(grow_sortlst, (float(str(detail.get_percent_change_from_year_low())[0:-1]) +
                                              float(
                                                  str(detail.get_percent_change_from_200_day_moving_average())[0:-1]) +
                                              float(str(detail.get_percent_change_from_50_day_moving_average())[0:-1]) +
                                              float(str(detail.get_percent_change_from_year_high())[0:-1]), stock,
                                              detail))
                if len(grow_sortlst) > 3:
                    heapq.heappop(grow_sortlst)
            total_f = 0
            for item in grow_sortlst:
                total_f = total_f + item[0]
            for item in grow_sortlst:
                item_pct = item[0]/float(total_f*iv_type)
                item_amt = allotment*item_pct
                rstlist.append({"sticker":item[1],"name":item[2].get_name(),"aloc_pct":str(item_pct),"aloc_amt":str(item_amt),"price":str(item[2].get_price()),"exchange":str(item[2].get_stock_exchange())})

        if 'index' in request.POST.keys():

            VTI = Share('VTI')
            vti_f = float(str(VTI.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(VTI.get_percent_change_from_200_day_moving_average())[0:-1]) - \
                     float(str(VTI.get_percent_change_from_year_high())[0:-1])

            IXUS = Share('IXUS')
            ixus_f = float(str(IXUS.get_percent_change_from_year_low())[0:-1]) + \
                     float(str(IXUS.get_percent_change_from_200_day_moving_average())[0:-1]) - \
                     float(str(IXUS.get_percent_change_from_year_high())[0:-1])

            ILTB = Share('ILTB')
            iltb_f = float(str(ILTB.get_percent_change_from_year_low())[0:-1]) + \
                      float(str(ILTB.get_percent_change_from_200_day_moving_average())[0:-1]) - \
                      float(str(ILTB.get_percent_change_from_year_high())[0:-1])
            stckdict['VTI'] = VTI
            stckdict['IXUS'] = IXUS
            stckdict['ILTB'] = ILTB
            total_f = (vti_f + ixus_f + iltb_f)*iv_type
            vti_pct = vti_f / float(total_f)
            ixus_pct = ixus_f / float(total_f)
            iltb_pct = iltb_f / float(total_f)
            vtiD = {"sticker": "VTI", "name": VTI.get_name(), "aloc_pct": str(vti_pct),
                     "aloc_amt": str(allotment * vti_pct), "price": str(VTI.get_price()),
                     "exchange": str(VTI.get_stock_exchange())}
            ixusD = {"sticker": "IXUS", "name": IXUS.get_name(), "aloc_pct": str(ixus_pct),
                     "aloc_amt": str(allotment * ixus_pct), "price": str(IXUS.get_price()),
                     "exchange": str(IXUS.get_stock_exchange())}
            iltbD = {"sticker": "ILTB", "name": ILTB.get_name(), "aloc_pct": str(iltb_pct),
                      "aloc_amt": str(allotment * iltb_pct), "price": str(ILTB.get_price()),
                      "exchange": str(ILTB.get_stock_exchange())}
            rstlist.append(vtiD)
            rstlist.append(ixusD)
            rstlist.append(iltbD)

        if 'quality' in request.POST.keys():
            for stock in quality_stcklist:
                while True:
                    try:
                        detail = Share(stock)
                    except:
                        time.sleep(0.1)
                        continue
                    break
                stckdict[stock] = detail
                heapq.heappush(quality_sortlst, (
                    float(detail.get_price_earnings_ratio() if detail.get_price_earnings_ratio() != None else 0) +
                    float(
                        detail.get_price_earnings_growth_ratio() if detail.get_price_earnings_growth_ratio() != None else 0) +
                    float(
                        detail.get_change_from_200_day_moving_average() if detail.get_change_from_200_day_moving_average() != None else 0) +
                    float(
                        detail.get_price_earnings_growth_ratio() if detail.get_price_earnings_growth_ratio() != None else 0),
                    stock, detail))
                if len(quality_sortlst) > 3:
                    heapq.heappop(quality_sortlst)
            total_f = 0
            for item in quality_sortlst:
                total_f = total_f + item[0]
            for item in quality_sortlst:
                item_pct = item[0] / float(total_f*iv_type)
                item_amt = allotment * item_pct
                rstlist.append({"sticker": item[1], "name": item[2].get_name(), "aloc_pct": str(item_pct),
                                "aloc_amt": str(item_amt), "price": str(item[2].get_price()),
                                "exchange": str(item[2].get_stock_exchange())})

        if 'value' in request.POST.keys():
            for stock in value_stcklist:
                while True:
                    try:
                        detail = Share(stock)
                    except:
                        time.sleep(0.1)
                        continue
                    break
                stckdict[stock] = detail
                heapq.heappush(value_sortlst,
                               (float(detail.get_dividend_yield() if detail.get_dividend_yield() != None else 0) +
                                float(
                                    detail.get_price_earnings_growth_ratio() if detail.get_price_earnings_growth_ratio() != None else 0) -
                                float(detail.get_price_book() if detail.get_price_book() != None else 0), stock,
                                detail))
                if len(value_sortlst) > 3:
                    heapq.heappop(value_sortlst)
            total_f = 0
            for item in value_sortlst:
                total_f = total_f + item[0]
            print "total_f=" + str(total_f)
            for item in value_sortlst:
                item_pct = item[0] / float(total_f*iv_type)
                item_amt = allotment * item_pct
                rstlist.append({"sticker": item[1], "name": item[2].get_name(), "aloc_pct": str(item_pct),
                                "aloc_amt": str(item_amt), "price": str(item[2].get_price()),
                                "exchange": str(item[2].get_stock_exchange())})
        days_cnt = 15
        str_date =  str((datetime.now() - timedelta(days=days_cnt)).date().isoformat())
        end_date = str(datetime.today().date().isoformat())
        day_pro = list()
        remaining = 0
        for item in rstlist:
            while True:
                try:
                    hist_info = stckdict[item["sticker"]].get_historical(str_date,end_date)
                except:
                    continue
                break
            for i in range(0,6):
                if len(day_pro)<=i:
                    day_pro.append({hist_info[i]["Date"]:float(hist_info[i]["Close"])*int(float(item["aloc_amt"])/float(hist_info[i]["Open"]))+float(item["aloc_amt"])%float(hist_info[i]["Open"])})
                else:
                    day_pro[i][hist_info[i]["Date"]] = float(day_pro[i][hist_info[i]["Date"]]) + float(hist_info[i]["Close"])*int(float(item["aloc_amt"])/float(hist_info[i]["Open"])) + float(item["aloc_amt"])%float(hist_info[i]["Open"])
        rstlist.append({"sticker":"portfolio","history":day_pro})
        print(json.dumps(rstlist))
        return render(request, 'portfolio/result.html', {'result': json.dumps(rstlist)})
    return render(request, 'portfolio/home.html')