예제 #1
0
def get_bond_his_rate(stockcode, date, ifcache=True):

    dict = get_cache()
    if ifcache and (stockcode, date) in dict.keys():
        #print("hit")
        return dict[(stockcode, date)]

    timestamp = int(time.mktime(date.timetuple()) * 1000)
    #print(timestamp)

    url = "https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol=$stockcode&begin=$timestamp&period=day&count=-1"
    url = url.replace("$stockcode", stockcode).replace("$timestamp", str(timestamp))
    #print(url)

    session = requests.Session()
    session.headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
    session.get('https://xueqiu.com/')
    r = session.get(url)
    #print(r.content)
    j = json.loads(r.content)

    date_get = datetime.datetime.fromtimestamp(j['data']['item'][0][0] / 1000.0).date()
    close = float(j['data']['item'][0][5])

    if date_get == date:
        #print("insert", stockcode, date, close)
        dict[stockcode, date] = close

    save_cache(dict)
    if (stockcode, date) in dict.keys():
        return dict[stockcode, date]
    else:
        return -1
예제 #2
0
def get_fund_his_price(stockcode, date, ifcache=True):
    dict = get_cache()
    if ifcache and (stockcode, date) in dict.keys():
        #print("hit")
        return dict[(stockcode, date)]

    url = "http://stock.finance.sina.com.cn/fundInfo/api/openapi.php/CaihuiFundInfoService.getNav?symbol=$stockcode&datefrom=$datefrom&dateto=$dateto&page=1"
    url = url.replace("$stockcode", stockcode[2:]).replace(
        "$dateto", date.strftime("%Y-%m-%d")).replace(
            "$datefrom",
            (date - relativedelta(months=+2)).strftime("%Y-%m-%d"))
    #print(url)
    r = requests.get(url)
    #print(r.content)
    j = json.loads(r.content)
    #print(j)

    for data in j['result']['data']['data']:
        time = datetime.datetime.strptime(data['fbrq'],
                                          '%Y-%m-%d %H:%M:%S').date()
        price = float(data['jjjz'])
        #print("insert", stockcode, time, price)
        dict[stockcode, time] = price

    save_cache(dict)

    if (stockcode, date) in dict.keys():
        return dict[stockcode, date]
    else:
        return -1
예제 #3
0
def get_stock_his_price(stockcode, date, ifcache=True):
    dict = get_cache()
    if ifcache and (stockcode, date) in dict.keys():
        #print("hit")
        return dict[(stockcode, date)]

    url = "http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/" + \
        "$stockcode.phtml?year=$year&jidu=$jidu"
    url = url.replace("$stockcode", stockcode).replace("$year", str(date.year)) \
        .replace("$jidu", str((date.month + 2)//3))
    print(url)
    r = requests.get(url)
    result = r.content.decode('GBK')
    print(result)
    bs = BeautifulSoup(result, "html.parser")
    table = bs.find('table', id='FundHoldSharesTable')
    #print(table)
    for idx, tr in enumerate(table):
        if idx >= 5 and idx % 2 == 1:
            #print(idx, tr)
            for idx2, td in enumerate(tr):
                if idx2 == 1:
                    time = datetime.datetime.strptime(td.text.strip(),
                                                      '%Y-%m-%d').date()
                elif idx2 == 7:
                    price = float(td.text.strip())
            #print("insert", stockcode, time, price)
            dict[stockcode, time] = price

    save_cache(dict)
    if (stockcode, date) in dict.keys():
        return dict[stockcode, date]
    else:
        return -1
예제 #4
0
def his_hs300(date, ifcache = True):
    dict = get_cache()
    if ifcache and ("hs300", date) in dict.keys():
        #print("hit")
        return dict["hs300", date]

    # 登陆系统
    lg = bs.login()
    # 显示登陆返回信息
    #print('login respond error_code:'+lg.error_code)
    #print('login respond  error_msg:'+lg.error_msg)

    # 获取沪深300成分股
    rs = bs.query_hs300_stocks(str(date))
    #print('query_hs300 error_code:'+rs.error_code)
    #print('query_hs300  error_msg:'+rs.error_msg)

    # 打印结果集
    hs300_stocks = []
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        hs300_stocks.append(rs.get_row_data())
    result = pd.DataFrame(hs300_stocks, columns=rs.fields)
    # 结果集输出到csv文件
    #print(result)
    datas = []
    for data in hs300_stocks:
        datas.append(data[1])

    if ifcache:
        dict["hs300", date] = datas
        save_cache(dict)

    # 登出系统
    bs.logout()
    return datas
예제 #5
0
def get_hkstock_his_price(stockcode, date, ifcache=True):
    #print("f**k")
    dict = get_cache()
    if ifcache and (stockcode, date) in dict.keys():
        #print("hit")
        return dict[(stockcode, date)]

    url = "http://stock.finance.sina.com.cn/hkstock/history/$stockcode.html"
    params = {"year": str(date.year), "season": str((date.month + 2) // 3)}
    url = url.replace("$stockcode", stockcode[2:])

    r = requests.post(url, data=params)
    #print(r.request.body)

    result = r.content.decode('GBK')
    #print(result)
    bs = BeautifulSoup(result, "html.parser")
    table = bs.find('tbody')
    #print(table)
    for idx, tr in enumerate(table):
        if idx >= 3 and idx % 2 == 1:
            # print(idx, tr)
            for idx2, td in enumerate(tr):
                if idx2 == 1:
                    time = datetime.datetime.strptime(td.text.strip(),
                                                      '%Y%m%d').date()
                elif idx2 == 3:
                    price = float(td.text.strip())
            #print("insert", stockcode, time, price)
            dict[stockcode, time] = price
    save_cache(dict)

    if (stockcode, date) in dict.keys():
        return dict[stockcode, date]
    else:
        return -1