Example #1
0
def getDistanceAndTimeByLngLat(origin, destination):
    url = unicode(
        'http://restapi.amap.com/v3/direction/driving?key={0}&origin={1}&destination={2}&strategy=9'
    ).format(getKey(), origin, destination)
    res = httpGet(url)

    jo = json.loads(res)
    if (int(jo['status']) == 0):
        writeWarningLog(
            unicode("【高德】驾车 路径规划失败, origin:{0},destination:{1},原因:{2}").format(
                origin, destination, jo))
        return (None, None)

    paths = jo['route']['paths']
    if (len(paths) <= 0):
        writeWarningLog(
            unicode(
                "【高德】驾车 没有找到相关路径, origin:{0},destination:{1},原因:{2}").format(
                    origin, destination, jo))
        return (None, None)

    distance = unicode("{0}公里").format(
        round(float(paths[0]['distance']) / 1000, 1))
    minutes = int(float(paths[0]['duration']) / 60)
    hour = int(minutes / 60)
    minute = int(minutes % 60)
    time = unicode("{0}分").format(minute) if hour <= 0 else unicode(
        "{0}小时{1}分").format(hour, minute)

    return (distance, time)
Example #2
0
def getStockListData(index, code, avgPE):
    page = 1
    listData = getListData(code, page)
    if listData is None:
        writeWarningLog("没有获取到第" + str(page) + "页的股票数据")
        return

    result = []
    dicDuplicate = {}
    result.append(
        unicode("{0},{1},{2},{3},{4},{5},{6},{7},{8}\n").format(
            "代码", "名称", "PE", "E2017", "E2018", "E2019", "复合", "排名",
            "PEG").encode('gbk'))

    needFetchNextPage = handleListData(listData["rank"], avgPE, result,
                                       dicDuplicate)

    totalPages = listData["pages"]
    if needFetchNextPage is None:
        for i in range(2, totalPages + 1):
            listData = getListData(code, i)
            if listData is None:
                writeWarningLog("没有获取到第" + str(i) + "页的股票数据")
                return

            needFetchNextPage = handleListData(listData["rank"], avgPE, result,
                                               dicDuplicate)
            if (needFetchNextPage == -1):
                break

    saveFile("bigData_" + code + ".csv", result)
    saveToDb(index + 1, result)
Example #3
0
def getBiasData(code, days):
    nAvg = getNAvg(code, days)
    '''weekday = datetime.today().weekday()
    datediff = 0
    if weekday % 7 == 0:
        datediff = 3
    elif weekday > 4:
        datediff = weekday - 4
    else:
        datediff = 1

    datediff = 0 if datetime.now().hour >= 19 else datediff
    startdate = (datetime.now() - timedelta(days=datediff)).strftime('%Y-%m-%d')
    print startdate, datediff'''

    today = datetime.now().strftime('%Y-%m-%d')
    data = tushareApi.getOneSpecifiedPriceHistoryData(
        code, today, today
    ) if datetime.now().hour >= 19 else tushareApi.getRealTimeData(code)

    if data <= 0:
        writeWarningLog(unicode('未获取到今日收盘价:' + code))
        return 0

    todayClosePrice = float(data)

    # print data, todayClosePrice
    return (todayClosePrice - nAvg) * 100 / nAvg
Example #4
0
def getStockListData(index, type, avgPE):
    page = 1
    listData = getListData(type, page)
    if listData is None:
        writeWarningLog("没有获取到第" + str(page) + "页的股票数据")
        return

    result = []
    dicDuplicate = {}
    result.append(
        unicode("{0},{1},{2},{3},{4},{5},{6},{7}\n").format(
            "代码", "名称", "PE", "PEG", "预测PEG", "No1(代码:名称:PEG)",
            "No2(代码:名称:PEG)", "No3(代码:名称:PEG)").encode('gbk'))

    needFetchNextPage = handleListData(listData, avgPE, result, dicDuplicate)

    if needFetchNextPage is None:
        for i in range(2, 200):
            listData = getListData(type, i)
            if listData is None:
                writeWarningLog("没有获取到第" + str(i) + "页的股票数据")
                return

            needFetchNextPage = handleListData(listData, avgPE, result,
                                               dicDuplicate)
            if (needFetchNextPage == -1):
                break

    saveFile("bigData_" + type + ".csv", result)
    saveToDb(index + 1, result)
Example #5
0
 def sendWeChatMessage(self, receiver, message):
     try:
         if self.senders.has_key(receiver):
             self.senders.get(receiver).send(message)
         else:
             writeWarningLog(
                 'sender is not exist: receiver: {0}, message: {1}'.format(
                     receiver, message))
     except Exception, e:
         writeErrorLog(
             'send we chat failed: receiver: {0}, message: {1}, e: {2}'.
             format(receiver, message, str(e)))
Example #6
0
def getGeoCodes(address):
    url = unicode(
        "http://restapi.amap.com/v3/geocode/geo?key={0}&address={1}&batch=true"
    ).format(getKey(), address)
    res = httpGet(url)

    jo = json.loads(res)

    if (int(jo['status']) == 0):
        writeWarningLog(
            unicode("【高德】解析地址失败, address:{0}, 原因:{1}").format(address, jo))
        return (None, None)

    result = []
    for i in range(0, len(jo['geocodes'])):
        geoCodes = jo['geocodes'][i]
        result.append(geoCodes['location'])

    return result
Example #7
0
def getPEG(code):
    market = "sh" if code.startswith("6") else "sz"
    url = "http://emweb.securities.eastmoney.com/PC_HSF10/IndustryAnalysis/IndustryAnalysisAjax?code=" + market + code + "&icode=" + str(
        random.randint(100, 999))
    res = httpGet(url).decode("utf-8")
    jo = json.loads(res)
    print jo
    rate = 0
    PEG = 0
    if (jo is not None and jo["Result"]["gzbj"] is not None
            and jo["Result"]["gzbj"]["data"] is not None):
        if (jo["Result"]["gzbj"]["data"][0]["dm"] != code):
            writeWarningLog("估值比较的股票代码没找到,实际代码:" + code + ",当前代码:" +
                            jo["Result"]["gzbj"]["data"][0]["dm"])
        else:
            rate = jo["Result"]["gzbj"]["data"][0]["pm"]
            PEG = jo["Result"]["gzbj"]["data"][0]["peg"]
            PEG = 0 if '--' in PEG else PEG

    if (jo is None or jo["Result"]["czxbj"] is None
            or jo["Result"]["czxbj"]["data"] is None
            or len(jo["Result"]["czxbj"]["data"]) <= 0):
        return (rate, PEG, 0, 0, 0, 0)

    e2017 = 0
    e2018 = 0
    e2019 = 0
    mixThree = 0

    if (jo["Result"]["czxbj"]["data"][0]["dm"] != code):
        writeWarningLog("成长性比较的股票代码没找到,实际代码:" + code + ",当前代码:" +
                        jo["Result"]["czxbj"]["data"][0]["dm"])
    else:
        mixThree = jo["Result"]["czxbj"]["data"][0]["jbmgsyzzlfh"]
        e2017 = jo["Result"]["czxbj"]["data"][0]["jbmgsyzzl1"]
        e2018 = jo["Result"]["czxbj"]["data"][0]["jbmgsyzzl2"]
        e2019 = jo["Result"]["czxbj"]["data"][0]["jbmgsyzzl3"]

    return (rate, PEG, mixThree, e2017, e2018, e2019)
Example #8
0
def getDirectionByLngLat(origin, destination):
    url = unicode(
        'http://restapi.amap.com/v3/direction/transit/integrated?key={0}&origin={1}&destination={2}&strategy=0&city=天津市'
    ).format(getKey(), origin, destination)
    res = httpGet(url)

    try:
        jo = json.loads(res)
        if (int(jo['status']) == 0):
            writeWarningLog(
                unicode(
                    "【高德】公交 路径规划失败, origin:{0},destination:{1},原因:{2}").format(
                        origin, destination, jo))
            return None

        transits = jo['route']['transits']
        if (len(transits) <= 0):
            writeWarningLog(
                unicode("【高德】公交规划 没有找到相关路径, origin:{0},destination:{1},原因:{2}"
                        ).format(origin, destination, jo))
            return None

        transit = transits[0]  # 找第一条规划路线
        segments = transit['segments']  # 路径信息

        if (len(segments) <= 0):
            writeWarningLog(
                unicode("【高德】公交规划 没有找到路径信息, origin:{0},destination:{1},原因:{2}"
                        ).format(origin, destination, jo))
            return None

        result = []
        for i in range(0, len(segments)):
            segment = segments[i]
            if i == 0:
                walkingDistance = round(
                    float(segment['walking']['distance']) / 1000, 1)
                walkingTime = int(float(segment['walking']['duration']) / 60)
                result.append(
                    unicode("步行{0}公里:约{1}分钟").format(walkingDistance,
                                                     walkingTime))

                busName = segment['bus']['buslines'][0]['name']
                busDepartureStop = segment['bus']['buslines'][0][
                    'departure_stop']['name']
                busArrivalStop = segment['bus']['buslines'][0]['arrival_stop'][
                    'name']
                totalStops = len(
                    segment['bus']['buslines'][0]['via_stops']) + 1
                result.append(
                    unicode("({0}) {1} => {2} 共{3}站").format(
                        busName, busDepartureStop, busArrivalStop, totalStops))
            elif i == len(segments) - 1:
                if segment['walking'] is not None:
                    if len(segment['walking']) <= 0:
                        continue
                    walkingDistance = round(
                        float(segment['walking']['distance']) / 1000, 1)
                    walkingTime = int(
                        float(segment['walking']['duration']) / 60)
                    result.append(
                        unicode("步行{0}公里:约{1}分钟").format(
                            walkingDistance, walkingTime))
            else:
                busName = segment['bus']['buslines'][0]['name']
                busDepartureStop = segment['bus']['buslines'][0][
                    'departure_stop']['name']
                busArrivalStop = segment['bus']['buslines'][0]['arrival_stop'][
                    'name']
                totalStops = len(
                    segment['bus']['buslines'][0]['via_stops']) + 1
                result.append(
                    unicode("({0}) {1} => {2} 共{3}站").format(
                        busName, busDepartureStop, busArrivalStop, totalStops))
        return result
    except Exception, e:
        traceback.print_exc()
        print url
        print res
        return None