Exemplo n.º 1
0
    def get_his_day_k(self, stockid, begindate, enddate):

        result = stock_dataset()
        result.name = stockid

        i = 0
        while i < self.repeat_num:
            try:
                url = "http://biz.finance.sina.com.cn/stock/flash_hq/kline_data.php?symbol=%s&begin_date=%s&end_date=%s" % (stockid, begindate, enddate)
                data = urllib.urlopen(url).read()
                tree = etree.HTML(data)

                contents = tree.xpath("//control/content")

                for content in contents:
                    stock = stock_data()
                    stock.date = content.xpath("./@d")[0]
                    stock.open_price = float(content.xpath("./@o")[0])
                    stock.high_price = float(content.xpath("./@h")[0])
                    stock.close_price = float(content.xpath("./@c")[0])
                    stock.low_price = float(content.xpath("./@l")[0])
                    stock.volumn = int(content.xpath("./@v")[0])

                    result.data.append(stock)

                break

            except Exception, ex:
                print ex.__str__()
                time.sleep(self.wait_gap)
                i = i + 1
                if i == self.repeat_num:
                    return None
Exemplo n.º 2
0
    def get_his_hour_k(self, stockid):

        result = stock_dataset()
        result.name = stockid

        i = 0
        while i < self.repeat_num:
            try:
                url = "http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=%s&scale=60&ma=no&datalen=1023" % (stockid)
                data = urllib.urlopen(url).read()
                
                data = data[2:-2]

                ary = data.split("},{")

                print len(ary)

                for item in ary:
                    stock = stock_data()

                    m = re.match(r'.*day:"(.*?)"', item)
                    stock.date = m.group(1)

                    m = re.match(r'.*open:"(.*?)"', item)
                    stock.open_price = float(m.group(1))

                    m = re.match(r'.*high:"(.*?)"', item)
                    stock.high_price = float(m.group(1))

                    m = re.match(r'.*close:"(.*?)"', item)
                    stock.close_price = float(m.group(1))

                    m = re.match(r'.*low:"(.*?)"', item)
                    stock.low_price = float(m.group(1))

                    m = re.match(r'.*volume:"(.*?)"', item)
                    stock.volumn = int(m.group(1))

                    result.data.append(stock)
                break

            except Exception, ex:
                print ex.__str__()
                time.sleep(self.wait_gap)
                i = i + 1
                if i == self.repeat_num:
                    return None
Exemplo n.º 3
0
    def refresh_his_day_file(self, stockid, days_num, file_name):
        fetcher = fund_fetcher()
        old_dataset = stock_dataset()
        new_data_list = []

        old_dataset.load_from_file(stockid, file_name)
        end_date = datetime.now().strftime("%Y%m%d")
        start_date = (datetime.now() - timedelta(days=days_num)).strftime("%Y%m%d")

        new_dataset = fetcher.get_his_day_k(stockid, start_date, end_date)

        for item in new_dataset.data:
            if old_dataset.get_data(item.date) == None:
                new_data_list.append(item)

        old_dataset.append_to_file(file_name, new_data_list)

        return
Exemplo n.º 4
0
    def refresh_his_day_file(self, stockid, days_num, file_name):
        fetcher = stock_fetcher()
        old_dataset = stock_dataset()
        new_data_list = []

        old_dataset.load_from_file(stockid, file_name)
        end_date = datetime.now().strftime("%Y%m%d")
        start_date = (datetime.now() -
                      timedelta(days=days_num)).strftime("%Y%m%d")

        new_dataset = fetcher.get_his_day_k(stockid, start_date, end_date)

        for item in new_dataset.data:
            if old_dataset.get_data(item.date) == None:
                new_data_list.append(item)

        old_dataset.append_to_file(file_name, new_data_list)

        return
Exemplo n.º 5
0
    def monitor(self, code):
        data_set = stock_dataset()
        data_set.load_from_file(code, "../data/" + code)

        #把今天的数据加入到data_set里
        fetcher = stock_fetcher()
        net = fetcher.get_present_price(code).close_price
        stock = stock_data()
        stock.close_price = net
        # today = datetime.now() - timedelta(days = 2)  #周末测试时使用
        today = datetime.now()
        today = today.strftime("%Y-%m-%d")
        stock.date = today
        data_set.data.append(stock)

        turtle_plan3 = turtle()
        result = turtle_plan3.get_trading_plan3(data_set, today)
        result["code"] = code

        f = open("../result/turtle3_result", "r+")
        line = f.readline()
        f.close()
        if line.startswith("#"):
            result["share"] = 0
            result["cost"] = 0
            return result
        arr = line.strip().split("|")
        result["share"] = arr[5]
        result["cost"] = arr[6]
        # if(result["choise"] == 4):  #buy
        #     result["share"] = round((money * (1 - DEAL_RATE) / result["close_price"]), 3)
        #     result["money"] = round(money * (1 - DEAL_RATE), 3)
        #     result["profit"] = profit
        #     self.append_result_to_file(filename, result, delim)
        # elif(result["choise"] == 2): #sell
        #     result["share"] = share
        #     result["money"] = round(result["close_price"] * share * (1 - DEAL_RATE), 3)
        #     result["profit"] = result["money"] - money
        #     self.append_result_to_file(filename, result, delim)
        return result
Exemplo n.º 6
0
class fund_fetcher(object):
    def __init__(self):
        return

    def get_his_day_k(self, fundid, begindate, enddate):

        raw_result = []

        try:
            begindate_str = datetime.strptime(begindate,
                                              "%Y%m%d").strftime("%Y-%m-%d")
            enddate_str = datetime.strptime(enddate,
                                            "%Y%m%d").strftime("%Y-%m-%d")

            url = "http://fund.eastmoney.com/f10/F10DataApi.aspx?type=lsjz&code=%s&page=1&per=5000&sdate=%s&edate=%s&rt=0.7955276783627965"\
                % (fundid, begindate_str, enddate_str)

            data = urllib.urlopen(url).read()
            m = re.match(r'.*content:"(.*)"', data)
            html_data = m.group(1)
            tree = etree.HTML(html_data)
            contents = tree.xpath("//tbody/tr")

            for content in contents:
                try:
                    tmp = {}
                    date = content.xpath("./td/text()")[0]
                    close_price = float(content.xpath("./td/text()")[1])
                    acc_close_price = float(content.xpath("./td/text()")[2])
                    rise_rate = float(
                        content.xpath("./td/text()")[3][:-1]) / 100
                    buy_status = content.xpath("./td/text()")[4]
                    sell_status = content.xpath("./td/text()")[5]
                    #meta = content.xpath("./td/text()")[6]

                    tmp["date"] = date
                    tmp["close_price"] = close_price
                    tmp["acc_close_price"] = acc_close_price
                    tmp["rise_rate"] = rise_rate
                    tmp["buy_status"] = buy_status
                    tmp["sell_status"] = sell_status
                    #tmp["meta"] = meta

                    raw_result.append(tmp)
                except Exception, ex:
                    continue

        except Exception, ex:
            print ex.__str__()
            return None

        raw_result.reverse()
        for i in range(len(raw_result)):
            if i != 0:
                raw_result[i]["acc_close_price"] = raw_result[
                    i - 1]["acc_close_price"] * (1 +
                                                 raw_result[i]["rise_rate"])

        dataset = stock_dataset()
        dataset.name = fundid

        for item in raw_result:
            stock = stock_data()
            stock.date = item["date"]
            stock.close_price = item["acc_close_price"]

            dataset.data.append(stock)

        return dataset
    def monitor(self, days_gap):

        sh000300_his = stock_dataset()
        sh000300_his.load_from_file("sh000300", "../data/sh000300")

        sh000905_his = stock_dataset()
        sh000905_his.load_from_file("sh000905", "../data/sh000905")

        sz399008_his = stock_dataset()
        sz399008_his.load_from_file("sz399008", "../data/sz399008")

        fetcher = stock_fetcher()

        sh000300_now = fetcher.get_present_price("sh000300")
        sh000905_now = fetcher.get_present_price("sh000905")
        sz399008_now = fetcher.get_present_price("sz399008")

        if sh000300_now == None or sh000905_now == None or sz399008_now == None:
            print "get now price error"
            return None

        if sh000300_now.date != sh000905_now.date or sh000300_now.date != sz399008_now.date:
            print "different date"
            return None

        last_valid_date = datetime.strptime(sh000300_his.data[0].date, "%Y-%m-%d")
        now_str = sh000300_now.date
        now = datetime.strptime(now_str, "%Y-%m-%d")
        last = now - timedelta(days=days_gap)

        while True:
            last_str = last.strftime("%Y-%m-%d")

            sh000300_last = sh000300_his.get_data(last_str)
            sh000905_last = sh000905_his.get_data(last_str)
            sz399008_last = sz399008_his.get_data(last_str)

            if sh000300_last != None and sh000905_last != None and sz399008_last:
                break
            else:
                last = last - timedelta(days=1)
                if last < last_valid_date:
                    return None

        sh000300_up = (sh000300_now.close_price - sh000300_last.close_price) / sh000300_last.close_price
        sh000905_up = (sh000905_now.close_price - sh000905_last.close_price) / sh000905_last.close_price
        sz399008_up = (sz399008_now.close_price - sz399008_last.close_price) / sz399008_last.close_price

        result = {}

        result["now_date"] = now_str
        result["last_date"] = last_str
        result["sh000300"] = [sh000300_last.close_price, sh000300_now.close_price, sh000300_up]
        result["sh000905"] = [sh000905_last.close_price, sh000905_now.close_price, sh000905_up]
        result["sz399008"] = [sz399008_last.close_price, sz399008_now.close_price, sz399008_up]

        if sh000300_up < 0 and sh000905_up < 0 and sz399008_up < 0:
            result["choise"] = "sell all"
            return result

        if sh000300_up > sh000905_up and sh000300_up > sz399008_up:
            result["choise"] = "sh000300"
        elif sh000905_up > sh000300_up and sh000905_up > sz399008_up:
            result["choise"] = "sh000905"
        elif sz399008_up > sh000300_up and sz399008_up > sh000905_up:
            result["choise"] = "sz399008"

        return result
Exemplo n.º 8
0
    close_prices = close_prices[99:]
    mean_price_10 = mean_price_10[99:]
    mean_price_100 = mean_price_100[99:]
    max_price_50 = max_price_50[99:]
    min_price_50 = min_price_50[99:]
    min_price_25 = min_price_25[99:]

    buy_index = [ num - 99 for num in buy_index]
    sell_half_index = [ num - 99 for num in sell_half_index]
    sell_all_index = [ num - 99 for num in sell_all_index]

    plt.figure(1)
    #plt.subplot(311)
    #plt.plot(close_prices, 'b-', mean_price_10, 'g-', mean_price_100, 'r-', max_price_50, 'c-', min_price_50, 'm-', min_price_25, 'y-', test_data, 'go')
    #plt.legend([dataset_name, "10 hour mean", "100 hour mean", "50 max price", '50 min price', '25 min price', 'test_data'], loc="upper left")

    plt.plot(close_prices, 'b-', mean_price_10, 'g-', mean_price_100, 'r-', max_price_50, 'c-', min_price_50, 'm-', min_price_25, 'y-', buy_index, buy, 'ro', sell_all_index, sell_all, 'go', sell_half_index, sell_half, 'g^')
    plt.legend([dataset_name, "10 hour mean", "100 hour mean", "50 max price", '50 min price', '25 min price', 'buy', 'sell_all', 'sell_half'], loc="upper left")
    plt.grid(True)

    plt.show()

    return

if __name__ == "__main__":

    sh000300_data = stock_dataset()
    sh000300_data.load_from_file("sh000300", "../data/sh000300_hour")

    test(sh000300_data, "sh000300", 100000)
Exemplo n.º 9
0
    sell_half_index = [num - 99 for num in sell_half_index]
    sell_all_index = [num - 99 for num in sell_all_index]

    plt.figure(1)
    #plt.subplot(311)
    #plt.plot(close_prices, 'b-', mean_price_10, 'g-', mean_price_100, 'r-', max_price_50, 'c-', min_price_50, 'm-', min_price_25, 'y-', test_data, 'go')
    #plt.legend([dataset_name, "10 hour mean", "100 hour mean", "50 max price", '50 min price', '25 min price', 'test_data'], loc="upper left")

    plt.plot(close_prices, 'b-', mean_price_10, 'g-', mean_price_100, 'r-',
             max_price_50, 'c-', min_price_50, 'm-', min_price_25, 'y-',
             buy_index, buy, 'ro', sell_all_index, sell_all, 'go',
             sell_half_index, sell_half, 'g^')
    plt.legend([
        dataset_name, "10 hour mean", "100 hour mean", "50 max price",
        '50 min price', '25 min price', 'buy', 'sell_all', 'sell_half'
    ],
               loc="upper left")
    plt.grid(True)

    plt.show()

    return


if __name__ == "__main__":

    sh000300_data = stock_dataset()
    sh000300_data.load_from_file("sh000300", "../data/sh000300_hour")

    test(sh000300_data, "sh000300", 100000)