示例#1
0
def format_mkt_cap(_mktcaptxt):

    if "-" == _mktcaptxt:
        return "0"

    _mktcap = stock_util.rf(_mktcaptxt.replace("EUR","").replace("RMB","").replace("US","").replace("HK","").replace("$","").replace("*",""))
    if "US" in _mktcaptxt:
        _mktcap = "%.0f" % (_mktcap * 7.77)
    elif "RMB" in _mktcaptxt:
        _mktcap = "%.0f" % (_mktcap * 1.11)
    elif "EUR" in _mktcaptxt:
        _mktcap = "%.0f" % (_mktcap * 9.64)
    else:
        _mktcap = "%.0f" % _mktcap
    
    return _mktcap
示例#2
0
def get_us_stock_quote(code):

    code = code.upper().strip()
    url = "https://api.iextrading.com/1.0/stock/market/batch?symbols=%s&types=quote,stats" % code

    print("URL: [" + url + "]")
    quote_result = {}

    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

    r = requests.get(url, headers=headers)
    jsondata = r.text 
    data = json.loads(jsondata)
    #print(data)
    
    if (not code in data):
        return quote_result
        
    quote_obj = data[code]["quote"]
    stats_obj = data[code]["stats"]

    name = quote_obj["companyName"]

    if quote_obj["low"] == None: quote_obj["low"] = 0
    if quote_obj["high"] == None: quote_obj["high"] = 0
   
    l_range = str("%.2f - %.2f " % (quote_obj["low"], quote_obj["high"]))
    l_open = quote_obj["open"] if quote_obj["open"] else 0
    l_close = quote_obj["iexRealtimePrice"] if quote_obj["iexRealtimePrice"] else 0
    
    if (l_close == 0 ):
        l_close = quote_obj["close"] if quote_obj["close"] else 0

    if (quote_obj["latestUpdate"]): 
        last_update = str(datetime.fromtimestamp(quote_obj["latestUpdate"]/1000.0).strftime('%Y-%m-%d %H:%M:%S'))
    else:
        last_update = None

    change_val = quote_obj["change"] if quote_obj["change"] else 0
    quote_obj["changePercent"] = quote_obj["changePercent"] if quote_obj["changePercent"] else 0
 
    if quote_obj["changePercent"]:
        change_pct = ("%.2f" % (quote_obj["changePercent"]*100)) + "%"
    else:
        change_pct = 0

    volume = str(quote_obj["latestVolume"])
    mean_vol = str(quote_obj["avgTotalVolume"])

    if (mean_vol):
        f_vol_now = stock_util.rf(volume)
        f_vol_avg = stock_util.rf(mean_vol)
        quote_result["V2V"] = 0
        
        if float(f_vol_avg) > 0:
            quote_result["V2V"] = "%.2f" % (float(f_vol_now) / float(f_vol_avg))

    if ("0.00" in volume):
        turnover = "N/A"
        quote_result["Volume"] = volume
        quote_result["Turnover"] = turnover
    else:
        turnover = "%.2f" % (float(volume) * float(l_close))
        quote_result["Volume"] = stock_util.rf2s(float(volume.strip("\r\n")))
        quote_result["Turnover"] = stock_util.rf2s(float(turnover))

    mkt_cap = stock_util.rf2s(quote_obj["marketCap"])
    pe_ratio = quote_obj["peRatio"]
    
    wk_low = quote_obj["week52Low"]
    wk_high = quote_obj["week52High"]

    dividend = stats_obj["dividendRate"]
    _yield = stats_obj["dividendYield"]
    
    #print("div %s, yield %s" % (dividend, _yield))

    eps = stats_obj["ttmEPS"]
    shares = stats_obj["sharesOutstanding"]
    beta = stats_obj["beta"]
        
    quote_result["CodeName"] = name
    quote_result["Close"] = l_close
    quote_result["ChangeVal"] = change_val
    quote_result["ChangePercent"] = change_pct

    if (quote_result["ChangeVal"] < 0):
        quote_result["Direction"] = "DOWN"
    elif (quote_result["ChangeVal"] == 0):
        quote_result["Direction"] = "NONE"
    else:
        quote_result["Direction"] = "UP"
        quote_result["ChangeVal"] = "+" + str(quote_result["ChangeVal"])
        quote_result["ChangePercent"] = "+" + str(quote_result["ChangePercent"])
    
    quote_result["MktCap"] = mkt_cap

    quote_result["Range"] = l_range

    quote_result["Open"] = l_open

    quote_result["LastUpdate"] = last_update

    quote_result["PE"] = pe_ratio
    
    if (_yield):
        quote_result["Yield"] = _yield
    if (dividend):
        quote_result["DivRatio"] = dividend
    quote_result["EPS"] = eps
    quote_result["Shares"] = shares
    quote_result["Beta"] = beta

    quote_result["52WeekLow"] = wk_low
    quote_result["52WeekHigh"] = wk_high
   
    return quote_result
示例#3
0
def rf(text):
    return stock_util.rf(text)
def get_jp_stock_quote(code):

    code = code.upper().strip()
    url = "https://quotes.wsj.com/JP/%s" % code

    print("URL: [" + url + "]")
    quote_result = {}

    headers = {
        'User-Agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
    }

    r = requests.get(url, headers=headers)
    html = r.text
    soup = BeautifulSoup(html, "html.parser")

    nameSpan = soup.find('span', {"class": "companyName"})

    if (not nameSpan):
        return quote_result

    infoUl = soup.findAll('ul', {"class": "cr_data_collection"})[0]
    cDataUl = soup.findAll('ul', {"class": "cr_data_collection"})[1]

    name = nameSpan.text
    l_range = infoUl.findAll('li', {"class": "cr_data_row"})[2].find(
        'span', {
            "class": "data_data"
        }).text.replace(",", "")
    l_open = cDataUl.findAll('span',
                             {"class": "data_data"})[0].text.replace(",", "")
    l_close = str(
        soup.find('span', {
            "class": "cr_curr_price"
        }).text.replace(",", "").replace("¥", ""))

    last_update = soup.find('li', {"class": "crinfo_time"}).text.strip()

    change_val = soup.find('span', {"class": "diff_price"}).text
    change_pct = soup.find('span', {"class": "diff_percent"}).text

    volume = infoUl.findAll('li', {"class": "cr_data_row"})[0].find(
        'span', {
            "class": "data_data"
        }).text.replace(",", "")
    mean_vol = infoUl.findAll('li', {"class": "cr_data_row"})[1].find(
        'span', {
            "class": "data_data"
        }).text.replace(",", "")

    if (mean_vol):
        f_vol_now = stock_util.rf(volume)
        f_vol_avg = stock_util.rf(mean_vol)
        quote_result["V2V"] = "%.2f" % (float(f_vol_now) / float(f_vol_avg))

    if ("0" == volume):
        turnover = "N/A"
        quote_result["Volume"] = volume
        quote_result["Turnover"] = turnover
    else:
        turnover = "%.2f" % (float(volume) * float(l_close))
        quote_result["Volume"] = stock_util.rf2s(float(volume.strip("\r\n")))
        quote_result["Turnover"] = stock_util.rf2s(float(turnover))

    keyDataUl = soup.find('div', {
        "class": "cr_keystock_drawer"
    }).findAll("ul", {"class": "cr_data_collection"})[0]

    mkt_cap = str(
        keyDataUl.findAll("li", {"class": "cr_data_row"})[2].find("span").text)
    pe_ratio = str(
        keyDataUl.findAll("li", {"class": "cr_data_row"})[0].find("span").text)

    range52 = infoUl.findAll('li', {"class": "cr_data_row"})[3].find(
        'span', {
            "class": "data_data"
        }).text.replace(",", "")
    wk_low = range52.split("-")[0].strip()
    wk_high = range52.split("-")[1].strip()

    _yield = str(
        keyDataUl.findAll("li", {"class": "cr_data_row"})[5].find("span").text)

    #print("div %s, yield %s" % (dividend, _yield))

    eps = str(
        keyDataUl.findAll(
            "li",
            {"class": "cr_data_row"})[1].find("span").text.replace(",",
                                                                   "").strip())
    shares = str(
        keyDataUl.findAll(
            "li",
            {"class": "cr_data_row"})[3].find("span").text.replace(",", ""))

    quote_result["CodeName"] = name
    quote_result["Close"] = l_close
    quote_result["ChangeVal"] = change_val
    quote_result["ChangePercent"] = change_pct

    if ("-" in quote_result["ChangeVal"]):
        quote_result["Direction"] = "DOWN"
    elif (quote_result["ChangeVal"] == "0"):
        quote_result["Direction"] = "NONE"
    else:
        quote_result["Direction"] = "UP"
        quote_result["ChangeVal"] = "+" + quote_result["ChangeVal"]
        quote_result["ChangePercent"] = "+" + quote_result["ChangePercent"]

    quote_result["MktCap"] = mkt_cap

    quote_result["Range"] = l_range

    quote_result["Open"] = l_open

    quote_result["LastUpdate"] = last_update

    quote_result["PE"] = pe_ratio

    if (_yield):
        quote_result["Yield"] = _yield
    quote_result["EPS"] = eps
    quote_result["Shares"] = shares

    quote_result["52WeekLow"] = wk_low
    quote_result["52WeekHigh"] = wk_high

    return quote_result
示例#5
0
def get_us_stock_quote(code):

    url = "https://finance.google.com/finance?q=" + code

    #print("URL: [" + url + "]")
    quote_result = {}

    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

    r = requests.get(url, headers=headers)
    html = r.text 
    #print(html)
    soup = BeautifulSoup(html, "html.parser")
    
    div = soup.find("div", {"class": "appbar"})

    if (not div):
        return quote_result

    appdiv = soup.find("div", {"class": "appbar-snippet-primary"})

    if (not appdiv):
        return quote_result

    name = appdiv.text
    price_panel = soup.find("div", {"id": "price-panel"})
    snap_table = soup.findAll("table", {"class": "snap-data"})[0]
    snap_rows = snap_table.findAll("tr")
    l_range = snap_rows[0].findAll("td")[1].text.strip()
    l_open = snap_rows[2].findAll("td")[1].text.strip()
    l_close = price_panel.find("span", {"class": "pr"}).text.strip()

    if price_panel.find("span", {"class": "nwp"}): 
        last_update = price_panel.find("span", {"class": "nwp"}).text
    else:
        last_update = "N/A"
    #print(price_panel)
    change_info = price_panel.find("div", {"class": "id-price-change"}).text.strip()

    if change_info:
        change_val = change_info.split("(")[0].strip()
        change_pct = change_info.split("(")[1].replace(")","").strip()
    else:
        change_val = "0.00"
        change_pct = "0.00%"

    volume = snap_rows[3].findAll("td")[1].text.split("/")[0].replace(",","")
    if (len(snap_rows[3].findAll("td")[1].text.split("/")) > 1):
        mean_vol = snap_rows[3].findAll("td")[1].text.split("/")[1]
    else:
        mean_vol = None 

    if (mean_vol):
        f_vol_now = stock_util.rf(volume)
        f_vol_avg = stock_util.rf(mean_vol)
        quote_result["V2V"] = "%.2f" % (float(f_vol_now) / float(f_vol_avg))

    l_close = l_close.replace(",","").strip('\n')
 
    if ("0.00" in volume):
        turnover = "N/A"
        quote_result["Volume"] = volume.strip("\r\n")
        quote_result["Turnover"] = turnover
    elif (not stock_util.is_number(volume) and not stock_util.is_float(volume)): 
        volume = volume.strip()
        #print("[" + volume + "]")
        #print("[" + volume.strip()[:-1] + "]")
        turnover = "%.2f" % (float(volume[:-1]) * float(l_close)) + volume[-1]
        quote_result["Volume"] = volume.strip("\r\n")
        quote_result["Turnover"] = turnover
    else:
        turnover = "%.2f" % (float(volume) * float(l_close))
        quote_result["Volume"] = stock_util.rf2s(float(volume.strip("\r\n")))
        quote_result["Turnover"] = stock_util.rf2s(float(turnover))

    mkt_cap = snap_rows[4].findAll("td")[1].text.split("/")[0]
    pe_ratio = snap_rows[5].findAll("td")[1].text.split("/")[0]
    
    wk_low = snap_rows[1].findAll("td")[1].text.split("-")[0]
    wk_high = snap_rows[1].findAll("td")[1].text.split("-")[1]
    
    snap_table = soup.findAll("table", {"class": "snap-data"})[1]
    snap_rows = snap_table.findAll("tr")


    if (snap_rows[0].findAll("td")[1].text.strip() == "-"):
        dividend = None
        _yield = None
    elif (len(snap_rows[0].findAll("td")[1].text.split("/")) > 1):
        dividend = snap_rows[0].findAll("td")[1].text.split("/")[0]
        _yield = snap_rows[0].findAll("td")[1].text.split("/")[1]
    else:
        dividend = snap_rows[0].findAll("td")[1].text.split("/")[0]
        _yield = None 

    eps = snap_rows[1].findAll("td")[1].text.strip()
    shares = snap_rows[2].findAll("td")[1].text.strip()
    beta = snap_rows[3].findAll("td")[1].text.strip()
    inst_own = snap_rows[4].findAll("td")[1].text.strip()
    
    quote_result["CodeName"] = name.strip("\r\n")
    quote_result["Close"] = l_close.strip("\r\n")
    quote_result["ChangeVal"] = change_val.strip("\r\n")
    quote_result["ChangePercent"] = change_pct.strip("\r\n")

    if ("+" in quote_result["ChangeVal"]):
        quote_result["Direction"] = "UP"
    elif ("-" in quote_result["ChangeVal"]):
        quote_result["Direction"] = "DOWN"
    else:
        quote_result["Direction"] = "NONE"

    quote_result["MktCap"] = mkt_cap.strip("\r\n")

    quote_result["Range"] = l_range.strip("\r\n")

    quote_result["Open"] = l_open.strip("\r\n")

    quote_result["LastUpdate"] = last_update.replace("Real-time:","").strip("\r").strip("\n")

    quote_result["PE"] = pe_ratio.strip("\r\n")
    
    if (_yield):
        quote_result["Yield"] = _yield.strip("\r\n")
    if (dividend):
        quote_result["DivRatio"] = dividend.strip("\r\n")
    quote_result["EPS"] = eps.strip("\r\n")
    quote_result["Shares"] = shares.strip("\r\n")
    quote_result["Beta"] = beta.strip("\r\n")

    quote_result["52WeekLow"] = wk_low.strip()
    quote_result["52WeekHigh"] = wk_high.strip()
   
    return quote_result
def manageStockVol(code):
    
    st = m18_stock_quote.get_hk_stock_quote(code)
    print(code + " - " + st["Close"] + "/" + st["ChangePercent"] + "/" +  st["Volume"])
    result = stock_tech_db.update_stock_vol(code, st["Close"], st["ChangePercent"], stock_util.rf(st["Volume"]))
    return result
示例#7
0
def get_stock_quote(code):

    if(is_derivative(code)):
        return get_stock_quote_derivative(code)

    url = "http://www.aastocks.com/en/mobile/Quote.aspx?symbol=" + code

    #print("URL: [" + url + "]")
    
    quote_result = {}

    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

    r = requests.get(url, headers=headers)
    html = r.text 
    #print(html)
    soup = BeautifulSoup(html, "html.parser")
    
    # if no close result, just return empty
    if (not soup.find("td", {"class": "quote_table_header_text"}).text.strip()):
        return quote_result

    quote_result["CodeName"] = (soup.find("td", {"class": "quote_table_header_text"}).text)

    # replace with cname if available
    cname = stock_db.get_stock_name(code)
    if cname:
        quote_result["CodeName"] = quote_result["CodeName"] + '\n' + cname 
 
    div_last = soup.find("div", {"class": "text_last"})

    quote_result["Close"] = (div_last.text.strip().replace(",",""))

    td_last = soup.find("td", {"class": "cell_last"})
    quote_result["ChangeVal"] = (td_last.find_all("div")[2].find_all("span")[0].text)
    quote_result["ChangePercent"] = (td_last.find_all("div")[2].find_all("span")[1].text)

    if ("+" in quote_result["ChangeVal"]):
        quote_result["Direction"] = "UP"
    elif ("-" in quote_result["ChangeVal"]):
        quote_result["Direction"] = "DOWN"
    else:
        quote_result["Direction"] = "NONE"

    quote_result["Range"] = (td_last.find_all("div")[3].text.strip())

    td_last = soup.find("td", {"class": "cell_last_height"})
    quote_result["Open"] = (td_last.find_all("td")[2].find("span").text)
    quote_result["PrevClose"] = (td_last.find_all("td")[3].find("span").text)
    quote_result["Volume"] = (td_last.find_all("td")[4].find("span").text)

    f_vol_now = f_vol_avg_3mth = None

    if (stock_util.rf(quote_result["Volume"])):
        f_vol_now = float(stock_util.rf(quote_result["Volume"]))
    
    stk = stock_tech_db.get_stock_tech(code)
    #print(stk)
    if (stk and stk["_3MONTH_AVG_VOL"]):
        f_vol_avg_3mth = float(stk["_3MONTH_AVG_VOL"])

    if (f_vol_now and f_vol_avg_3mth):
        quote_result["V2V"] = "%.2f" % (f_vol_now / f_vol_avg_3mth)

    #quote_result[""] = (soup.find("div", {"class": "ctl00_cphContent_pQuoteDetail"}))
    div_content = soup.find("div", {"id": "ctl00_cphContent_pQuoteDetail"})
    quote_result["LastUpdate"] = (div_content.find("font", {"class": "font12_white"}).text)

    rows = div_content.find_all("table")[0].find_all("tr", recursive=False)

    quote_result["LotSize"] = (rows[2].find_all("td")[0].find("span").text)
    quote_result["Turnover"] = (rows[2].find_all("td")[1].find("span").text)
    quote_result["PE"] = (rows[3].find_all("td")[0].find("span").text)
    quote_result["Yield"] = (rows[3].find_all("td")[1].find("span").text)
    quote_result["DivRatio"] = (rows[4].find_all("td")[0].find("span").text)
    quote_result["EPS"] = (rows[4].find_all("td")[1].find("span").text)
    quote_result["MktCap"] = (rows[5].find_all("td")[0].find("span").text)
    quote_result["NAV"] = (rows[5].find_all("td")[1].find("span").text)

    div52 = soup.find("div", {"id": "ctl00_cphContent_p52Week"})
    
    if (div52.find("span").text == "N/A"):
        quote_result["52WeekLow"] = "N/A"
        quote_result["52WeekHigh"] = "N/A"
    else:
        quote_result["52WeekLow"] = (div52.find("span").text.split("-")[0].strip())
        quote_result["52WeekHigh"] = (div52.find("span").text.split("-")[1].strip())
    
    return quote_result