Пример #1
0
def do_index():
    _code = request.forms.get('code')
    code = _code.split(' ')[0]
    if len(_code.split(' ')) == 2:
        if _code.split(' ')[1] == 'y':
            start_date = dt.date.today() + relativedelta(years=-1)
        elif _code.split(' ')[1] == '3y':
            start_date = dt.date.today() + relativedelta(years=-3)
        else:
            start_date = None
    else:
        start_date = None
    jstock(code, start_date)
    search = jsm.Quotes().search(code)
    Name = search[0].name
    financialData = jsm.Quotes().get_finance(code)
    finance = [
        financialData.market_cap,
        financialData.shares_issued,
        financialData.dividend_yield,
        financialData.dividend_one,
        financialData.per,
        financialData.pbr,
        financialData.price_min,
        financialData.round_lot
    ]
    imagepath = 'image/{}.png'.format(code)
    txtpath = 'data/{}.txt'.format(code)
    return template('result', imagepath=imagepath, txtpath=txtpath, code=code, Name=Name, finance=finance)
Пример #2
0
    def get_candle_data(self):
        """株価データ(始値、高値、安値、終値、出来高、日付)を取得する"""
        _quotes = jsm.Quotes()
        try:
            _target = _quotes.get_historical_prices(self.code, jsm.WEEKLY,
                                                    self.start, self.end)
        except:
            print("存在しないコードです。")
            self.is_exist_code = False
            return

        # 株価情報をリスト形式に変換する
        _date = [_data.date.strftime("%Y-%m-%d") for _data in _target]
        _open = [_data.open for _data in _target]
        _close = [_data.close for _data in _target]
        _high = [_data.high for _data in _target]
        _low = [_data.low for _data in _target]
        _volume = [_data.volume for _data in _target]

        # 日付が古い順に並べ替える
        self.ohcl["date"] = _date[::-1]
        self.ohcl["open"] = _open[::-1]
        self.ohcl["close"] = _close[::-1]
        self.ohcl["high"] = _high[::-1]
        self.ohcl["low"] = _low[::-1]
        self.ohcl["volume"] = _volume[::-1]

        self.__get_current_candle_data()
Пример #3
0
    def stockgetweekjsm(self, start_date, end_date, stock_num):
        q = jsm.Quotes()
        stock = q.get_historical_prices(stock_num, jsm.WEEKLY, start_date,
                                        end_date)  #指定期間、指定銘柄の株価取得
        close_stock = [data.close for data in stock]  #終値の取得
        date_stock = [data.date for data in stock]  #日付の取得
        db_sw = Series(close_stock, date_stock)  #日付と終値をドッキング
        self.add_db_sw = db_sw.sort_index(ascending=True)  #古い順に並び替える。
        self.add_db_sw = DataFrame(self.add_db_sw,
                                   columns=['Stock'])  #列名'Stock'を付与する。
        #print("self.add_db_sw")
        #print(self.add_db_sw)
        #print("self.db_sw")
        #print(self.db_sw)

        #(try-catch)新規の銘柄の場合はself.db_sが存在しないため、except以降の処理:self.db_sw=self.add_db_swとする
        try:
            self.db_sw = self.db_sw.append(
                self.add_db_sw)  #既存の株価に新規に追加した株価を追加する
            self.db_sw = self.db_sw.groupby(level=0)  #重複行があれば削除する
            self.db_sw = self.db_sw.last()  #重複行があれば削除する
        #print("self.db_sw")
        #print(self.db_sw)
        except AttributeError:
            self.db_sw = self.add_db_sw

        self.db_sw.to_csv(setting.HOME_PATH + str(stock_num) + ".week.csv",
                          header=False)
        self.db_sw = DataFrame(self.db_sw, columns=['Stock'])  #列名'Stock'を付与する。
        return self.db_sw
Пример #4
0
def main():
	con = mysql.connector.connect(
		host    = config.db['host'],
		db      = config.db['db'],
		user    = config.db['user'],
		passwd  = config.db['passwd'],
		charset = "utf8"
	)
	cur = con.cursor()

	q = jsm.Quotes()

	"""Brandの取得"""
	brand = jsm.Brand()
	ids = brand.IDS # 業種コードのリスト

	brand_list = []
	for industory_code in ids.keys():
		industory_name = ids[industory_code]
		brand_data = q.get_brand(industory_code) # 業種ごとの属性情報の取得を行う

		for data in brand_data:
			ts = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
			
			try:
				cur.execute("INSERT INTO brands(ccode, industory_code, industory_name, market, name, info, created_at, updated_at) VALUES(%s, %s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE market = %s, updated_at = %s", (data.ccode, industory_code, industory_name, data.market, data.name, data.info, ts, ts, data.market, ts))
				con.commit()
			except:
				pass

	cur.close()
	con.close()
Пример #5
0
def get_stock(GET_STOCK_CODE, GET_START_DATE, GET_END_DATE):
    # Time Span
    S_YEAR, S_MONTH, S_DAY = GET_START_DATE.split("-")
    TARGET_START = datetime.date(int(S_YEAR), \
                                int(S_MONTH), \
                                int(S_DAY))
    E_YEAR, E_MONTH, E_DAY = GET_END_DATE.split("-")
    TARGET_END = datetime.date(int(E_YEAR), \
                                int(E_MONTH), \
                                int(E_DAY))

    # Get Stock Price
    Q = jsm.Quotes()
    TARGET = Q.get_historical_prices(GET_STOCK_CODE, \
                                     jsm.DAILY, \
                                     TARGET_START, \
                                     TARGET_END)

    # Return to list each quotes
    Q_DATE = [DATA.date for DATA in TARGET]
    Q_OPEN = [DATA.open for DATA in TARGET]
    Q_HIGH = [DATA.high for DATA in TARGET]
    Q_LOW = [DATA.low for DATA in TARGET]
    Q_CLOSE = [DATA.close for DATA in TARGET]
    Q_VOLUME = [DATA.volume for DATA in TARGET]
    return [Q_DATE, Q_OPEN, Q_HIGH, Q_LOW, Q_CLOSE, Q_VOLUME]
Пример #6
0
def get_stock(code, start_date, end_date):
    """ get_stock(stockcode, start_date, end_date) return DataFrame.
        index:date,
        columns:open, high, low, close, volume
    """
    start_date = todate(start_date)
    end_date = todate(end_date)

    q = jsm.Quotes()

    target = q.get_historical_prices(code,
                                     jsm.DAILY,
                                     start_date=start_date,
                                     end_date=end_date)
    diccolumns = {}
    diccolumns['date'] = [data.date for data in target]
    diccolumns['open'] = [data.open for data in target]
    diccolumns['high'] = [data.high for data in target]
    diccolumns['low'] = [data.low for data in target]
    diccolumns['close'] = [data.close for data in target]
    diccolumns['volume'] = [data.volume for data in target]

    columns = ['open', 'high', 'low', 'close', 'volume']
    df = pd.DataFrame(diccolumns, index=diccolumns['date'], columns=columns)
    df.index.name = 'date'
    df = df[::-1]
    return df
Пример #7
0
def get_stock(code, start_date, end_date):

    # 期間設定

    year, month, day = start_date.split("-")

    start = datetime.date(int(year), int(month), int(day))

    year, month, day = end_date.split("-")

    end = datetime.date(int(year), int(month), int(day))

    # 株価データ取得

    q = jsm.Quotes()

    target = q.get_historical_prices(code,
                                     jsm.DAILY,
                                     start_date=start,
                                     end_date=end)

    # 項目ごとにリストに格納して返す

    date = [data.date for data in target]

    open = [data.open for data in target]

    close = [data.close for data in target]

    high = [data.high for data in target]

    low = [data.low for data in target]

    # 日付が古い順に並び替えて返す
    return [date[::-1], open[::-1], close[::-1], high[::-1], low[::-1]]
Пример #8
0
    def stockgetweekjsm(self,start_date,end_date,stock_num):
        q = jsm.Quotes()
        stock = q.get_historical_prices(stock_num, jsm.WEEKLY, start_date, end_date)   #指定期間、指定銘柄の株価取得
        open_stock = [data.open for data in stock]  # 始値の取得
        high_stock = [data.high for data in stock]  # 高値の取得
        low_stock = [data.low for data in stock]  # 低値の取得
        close_stock = [data.close for data in stock]  # 終値の取得
        volume_stock = [data.volume for data in stock]  # 出来高の取得   
        date_stock = [data.date.date() for data in stock]  # 日付の取得(date()で時刻の情報を削除している)
        db_sw = pd.DataFrame([date_stock,close_stock,open_stock,high_stock,low_stock,volume_stock]).T   # 日付,始値,高値,低値,終値,出来高のマトリックスの作成
        db_sw.columns = ['DATE','CLOSE','OPEN','HIGH','LOW','VOL']
        db_sw=db_sw.set_index('DATE') # DATE列をindexに指定する  
        self.add_db_sw=db_sw.sort_index() # DATE列で古い順番に並べる


       #(try-catch)新規の銘柄の場合はself.db_sが存在しないため、except以降の処理:self.db_sw=self.add_db_swとする        
        try:     
            self.db_sw=self.db_sw.append(self.add_db_sw) #既存の株価に新規に追加した株価を追加する
            #print("check000")
            #self.db_sw=self.db_sw.drop_duplicates().sort_index()      #重複行があれば削除する & 日付が古い順番にデータを並べ替える
            self.db_sw=self.db_sw.drop_duplicates()      #重複行があれば削除する (sort_index()はエラーが出るため削除)
            #print("self.db_sw")
            #print(self.db_sw)           
        except AttributeError:
            self.db_sw=self.add_db_sw

        #self.db_sw.to_csv(setting.HOME_PATH + str(stock_num) +".week.csv",header=True)
        return self.db_sw
Пример #9
0
def get_data_yahoojp(symbols=None,
                     start=None,
                     end=None,
                     retry_count=3,
                     pause=0.001,
                     adjust_price=False,
                     ret_index=False,
                     chunksize=25):
    q = jsm.Quotes()

    if not isinstance(symbols, list):
        return data2frame(
            q.get_historical_prices(symbols, start_date=start, end_date=end))

    for i, s in enumerate(symbols):
        try:
            symbols[i] = int(s)
        except:
            raise exceptions.ValueError("symbols must be an integer")

    prices = []
    for symbol in symbols:
        prices.append(
            data2frame(
                q.get_historical_prices(symbol, start_date=start,
                                        end_date=end)))
    return prices
Пример #10
0
    def on_click2(self):
        gcode = int(self.combo.currentIndex())

        if gcode > 0:
            brandlist = [
                "0050", "1050", "2050", "3050", "3100", "3150", "3200", "3250",
                "3300", "3350", "3400", "3450", "3500", "3550", "3600", "3650",
                "3700", "3750", "3800", "4050", "5050", "5100", "5150", "5200",
                "5250", "6050", "6100", "7050", "7100", "7150", "7200", "8050",
                "9050"
            ]
            q = jsm.Quotes()
            target = q.get_brand(brandlist[gcode - 1])
            ccode = [data.ccode for data in target]
            market = [data.market for data in target]
            name = [data.name for data in target]
            info = [data.info for data in target]
            df = DataFrame(index=ccode)
            df.index.name = "証券コード"
            df["銘柄名"] = name
            df["市場"] = market
            df["インフォメーション"] = info
            df.to_csv(brandlist[gcode - 1] + '.csv')
            QMessageBox.question(self, 'Exported list',
                                 brandlist[gcode - 1] + '.csv を出力しました.',
                                 QMessageBox.Ok, QMessageBox.Ok)

            self.combo.setCurrentIndex(0)

        else:
            self.combo.setCurrentIndex(0)
Пример #11
0
def test_ccode_exception():
    q = jsm.Quotes()
    try:
        q.get_historical_prices('0000', jsm.DAILY)
    except CCODENotFoundException:
        return
    raise Exception('exception is not thrown')
Пример #12
0
def test_get_stock_split_date():
    q = jsm.Quotes()
    e = datetime.datetime(2014,6,27)
    s = datetime.datetime(2014,6,23)
    one = q.get_historical_prices(6858, jsm.DAILY, s, e)
    if len(one) != 5:
        raise Exception('invalid length')
Пример #13
0
def get_stock(code, start_date, end_date):
    try:
        aaa = int(code)
    except:
        # 米国株
        print("米国")
        result, date, open1, high, low, close, volume = get_stock_usd(code)
        return result, date, open1, high, low, close, volume, 0

    try:
        # 期間設定
        start_date = str(start_date).replace("-", "/")
        end_date = str(end_date).replace("-", "/")
        year, month, day = start_date.split("/")
        start = datetime.date(int(year), int(month), int(day))
        year, month, day = end_date.split("/")
        end = datetime.date(int(year), int(month), int(day))
        # 株価データ取得
        q = jsm.Quotes()
        target = q.get_historical_prices(code,
                                         jsm.DAILY,
                                         start_date=start,
                                         end_date=end)
        # 項目ごとにリストに格納して返す
        date = [data.date.strftime("%Y/%m/%d") for data in target]
        open = [data.open for data in target]
        high = [data.high for data in target]
        low = [data.low for data in target]
        close = [data.close for data in target]
        volume = [data.volume for data in target]
        adj_close = [data._adj_close for data in target]
        return 1, date, open, high, low, close, volume, adj_close
    except:
        return -1, 1, 1, 1, 1, 1, 1, 1
Пример #14
0
def test_get_fund_range_daily():
    q = jsm.Quotes()
    start_date = datetime.date.fromtimestamp(time.time() - 604800) # 1週間前
    end_date = datetime.date.today()
    one = q.get_historical_prices(FUND_CODE, jsm.DAILY, start_date, end_date)
    if not one:
        raise Exception('is None')
Пример #15
0
def test_get_range():
    q = jsm.Quotes()
    start_date = datetime.date.fromtimestamp(time.time() - 604800)  # 1週間前
    end_date = datetime.date.today()
    for range_type in (jsm.DAILY, jsm.WEEKLY, jsm.MONTHLY):
        one = q.get_historical_prices(CCODE, range_type, start_date, end_date)
        if not one:
            raise Exception('is None')
Пример #16
0
def get_jstock(code, freq='D', start=None, end=None, periods=None):
    """get Japanese stock data using jsm
    Usage:
        `get_jstock(6502)`
        To get TOSHIBA daily from today back to 30days except holiday.

        `get_jstock(6502, 'W', start=pd.Timestamp('2016'), end=pd.Timestamp('2017'))`
        To get TOSHIBA weekly from 2016-01-01 to 2017-01-01.

        `get_jstock(6502, end=pd.Timestamp('20170201'), periods=50)`
        To get TOSHIBA daily from 2017-02-01 back to 50days except holiday.

        `get_jstock(6502, 'M', start='first', end='last')`
        To get TOSHIBA monthly from 2000-01-01 (the date of start recording) to today.
    """
    # Default args
    if com._count_not_none(start, end, periods) == 0:  # All of args is None
        end, periods = 'last', 30

    # Switch frequency Dayly, Weekly or Monthly
    freq_dict = {'D': jsm.DAILY, 'W': jsm.WEEKLY, 'M': jsm.MONTHLY}

    # 'first' means the start of recording date
    if start == 'first':
        data = jsm.Quotes().get_historical_prices(code,
                                                  range_type=freq_dict[freq],
                                                  all=True)
        start = [i.date for i in data][-1]
    else:
        data = None  # Temporaly defined

    # 'last' means last weekday (or today)
    if end == 'last':
        end = pd.datetime.today()

    # Return "start" and "end"
    start, end = (x.date() if hasattr(x, 'date') else x
                  for x in set_span(start, end, periods, freq))
    print('Get data from {} to {}'.format(start, end))

    data = jsm.Quotes().get_historical_prices(
        code, range_type=freq_dict[freq], start_date=start,
        end_date=end) if not data else data
    df = _convert_dataframe(data)
    return df[start:end]
Пример #17
0
def test_get():
    q = jsm.Quotes()
    d = q.get_price(CCODE)
    assert isinstance(d, PriceData)
    assert isinstance(d.open, (int, float))
    assert isinstance(d.close, (int, float))
    assert isinstance(d.high, (int, float))
    assert isinstance(d.low, (int, float))
    assert isinstance(d.volume, int)
Пример #18
0
def test_search():
    q = jsm.Quotes()
    result = q.search('グリー')
    assert result[0].ccode == '3632'
    result = q.search('3632')
    assert result[0].ccode == '3632'
    result = q.search('NTTドコモ')
    assert result[0].ccode == '9437'
    result = q.search('0000')
    assert len(result) == 0
Пример #19
0
    def get_brand_info(self, classify_list):
        q = jsm.Quotes()

        print "getting brand info..."
        for classify in classify_list:
            print "classify:", classify
            brands_info = q.get_brand(classify)

            for b_info in brands_info:
                self.addtoindex(classify, b_info)
        self.dbcommit()
Пример #20
0
def appendstockcsv(code, range_type, start_date, end_date, stockdf):
    q = jsm.Quotes()
    prices = q.get_historical_prices(code, range_type, start_date, end_date)
    for price in prices:
        stockdf = stockdf.append(pd.Series(price_to_csvl(price),
                                           index=[
                                               'Date', 'Open', 'High', 'Low',
                                               'Close', 'Volume', 'AdjClose'
                                           ]),
                                 ignore_index=True)
        stockdf = stockdf.drop_duplicates().sort_values(by=["Date"],
                                                        ascending=False)
    return stockdf
Пример #21
0
    def getspjsm(self):
        cnn = pm.connect(host="127.0.0.1",
                         user="******",
                         password="******",
                         database="TS")
        cur = cnn.cursor()
        cur.execute("""SELECT BCCode FROM M_Business_Category_YH  """)
        rcds = cur.fetchall()
        cur.execute("""SELECT max([day]) FROM SP_Daily  """)
        curmaxday = cur.fetchall()
        q = j.Quotes()
        now = datetime.datetime.now()
        nowstr = '{0:%Y%m%d}'.format(now)

        curday = curmaxday[0][0]
        for cd in rcds:
            d = q.get_brand(cd[0])
            ccodes = [data.ccode for data in d]
            markets = [data.market for data in d]
            names = [data.name for data in d]
            infos = [data.info for data in d]
            data = [ccodes, markets, names, infos]

            for (ccode, market, name, info) in zip(*data):
                arg2 = (ccode, int(nowstr), market, name, info, cd[0])
                cur.callproc('UpdateStockInfo', arg2)
                cnn.commit()

                a = q.get_finance(ccode)
                market_cap = a.market_cap
                shares_issued = a.shares_issued
                dividend_yield = a.dividend_yield
                dividend_one = a.dividend_one
                per = a.per
                pbr = a.pbr
                eps = a.eps
                bps = a.bps
                price_min = a.price_min
                round_lot = a.round_lot
                years_high = a.years_high
                years_low = a.years_low

                arg2 = (ccode, int(curday), market_cap, shares_issued,
                        dividend_yield, dividend_one, per, pbr, eps, bps,
                        price_min, round_lot, years_high, years_low)
                print('[[' + ccode + ' ]]')
                cur.callproc('UpdateStockFinance', arg2)
                cnn.commit()
                print('[[' + ccode + ' Update Over]]')
        cnn.close()
Пример #22
0
    def on_click(self):
        code = int(self.textbox.text())
        ybegin = int(self.byear.text())
        mbegin = int(self.bmonth.text())
        dbegin = int(self.bdate.text())
        yend = int(self.eyear.text())
        mend = int(self.emonth.text())
        dend = int(self.edate.text())
        self.start = dt.date(ybegin, mbegin, dbegin)
        self.end = dt.date(yend, mend, dend)

        q = jsm.Quotes()
        target = q.get_historical_prices(code,
                                         jsm.DAILY,
                                         start_date=self.start,
                                         end_date=self.end)

        self.date = [data.date for data in target]
        self.open = [data.open for data in target]
        self.high = [data.high for data in target]
        self.low = [data.low for data in target]
        self.close = [data.close for data in target]
        self.volume = [data.volume for data in target]
        self.adj_close = [data._adj_close for data in target]

        self.Date = self.date[::-1]
        self.Open = self.open[::-1]
        self.High = self.high[::-1]
        self.Low = self.low[::-1]
        self.Close = self.close[::-1]
        self.Adj = self.adj_close[::-1]
        self.Vol = self.volume[::-1]

        cdf = DataFrame(index=self.Date)
        cdf.index.name = "Date"
        cdf["Open"] = self.Open
        cdf["High"] = self.High
        cdf["Low"] = self.Low
        cdf["Close"] = self.Close
        cdf["Adj Close"] = self.Adj
        cdf["Volume"] = self.Vol

        cdf.to_csv(str(code) + '.csv')

        QMessageBox.question(self, 'Exported CSV',
                             str(code) + '.csv を出力しました.', QMessageBox.Ok,
                             QMessageBox.Ok)

        self.textbox.setText("")
Пример #23
0
    def get_price_data(self, code):
        """ get new stack price data """
        table_name = 'price_master'

        q = jsm.Quotes()
        if self.isindexed(code):
            print 'Ticker symbol:' + str(code) + ' is ' + "updating data..."
            try:
                self.update_price_data(q, code)
                self.brand_info_db.execute(
                    "update brand_info_master set enable=1 where code=%s" %
                    code)
            except Exception, e:
                print "error:", e
                self.get_histrical_data(q, code)
Пример #24
0
def _get_price(text):
    try:
        q = jsm.Quotes()
        price = q.get_price(int(text))
        utime = int(time.mktime(price.date.timetuple()))
        price_date = datetime.fromtimestamp(utime, JST())

        return 'Stock price of {2} at {0} is JPY{1}'.format(
            price_date.strftime('%Y/%m/%d %H:%M:%S'),
            '{:,.02f}'.format(price.close), text)
        """
        for historical data
        """
        # prices = q.get_historical_prices(int(text), jsm.DAILY)
        # return "\n".join(map(lambda p:"{0}\tJPY{1}".format(p.date.strftime('%Y/%m/%d'), "{:,.02f}".format(p.close)), prices))
    except:
        return ''
Пример #25
0
def jpstock(code, start_date, end_date):
    year, month, day = start_date.split("-")
    start = dt.date(int(year), int(month), int(day))
    year, month, day = end_date.split("-")
    end = dt.date(int(year), int(month), int(day))

    print('CSVを出力中...')
    q = jsm.Quotes()
    target = q.get_historical_prices(code,
                                     jsm.DAILY,
                                     start_date=start,
                                     end_date=end)

    date = [data.date for data in target]
    open = [data.open for data in target]
    high = [data.high for data in target]
    low = [data.low for data in target]
    close = [data.close for data in target]
    volume = [data.volume for data in target]
    adj_close = [data._adj_close for data in target]

    Date = date[::-1]
    Open = open[::-1]
    High = high[::-1]
    Low = low[::-1]
    Close = close[::-1]
    Adj = adj_close[::-1]
    Vol = volume[::-1]

    cdf = DataFrame(index=Date)
    cdf.index.name = "Date"
    cdf["Open"] = Open
    cdf["High"] = High
    cdf["Low"] = Low
    cdf["Close"] = Close
    cdf["Adj Close"] = Adj
    cdf["Volume"] = Vol

    cdf.to_csv(code + '.csv')
    print(code + '.csvを出力しました.')

    print('株価データをプロット中...')
    df = DataFrame(index=Date)
    df['Adj Close'] = Adj

    return df
Пример #26
0
    def stockgetdayjsm(self, start_date, end_date, stock_num):
        q = jsm.Quotes()
        stock = q.get_historical_prices(stock_num, jsm.DAILY, start_date, end_date)  # 指定期間、指定銘柄の株価取得
        date_stock = [data.date.date() for data in stock]  # 日付の取得(date()で時刻の情報を削除している)  
        open_stock = [data.open for data in stock]  # 始値の取得
        high_stock = [data.high for data in stock]  # 高値の取得
        low_stock = [data.low for data in stock]  # 低値の取得
        close_stock = [data.close for data in stock]  # 終値の取得
        volume_stock = [data.volume for data in stock]  # 出来高の取得         
        db_s=pd.DataFrame([date_stock,close_stock,open_stock,high_stock,low_stock,volume_stock]).T   # 日付,始値,高値,低値,終値,出来高のマトリックスの作成
        db_s.columns = ['DATE','CLOSE','OPEN','HIGH','LOW','VOL']       
        db_s=db_s.set_index('DATE') # DATE列をindexに指定する  
        self.add_db_s=db_s.sort_index() # DATE列で古い順番に並べる
        #print("add_db_s")
        #print(self.add_db_s)  
        #self.add_db_s=self.add_db_s(axis='index')
        #self.add_db_s = DataFrame(self.add_db_s, columns=['Stock'])  #列名'Stock'を付与する。
        #print("self.db_s")
        #print(self.db_s)

        #(try-catch)新規の銘柄の場合はself.db_sが存在しないため、except以降の処理:self.db_s=self.add_db_sとする
        try:
            #print("self.add_db_s")
            #print(self.add_db_s) 
            #print(self.db_s)  
            self.db_s=self.db_s.append(self.add_db_s) #既存の株価に新規に追加した株価を追加する    
            #print("self.db_s") 
            #print(self.db_s)     
            #print("d0")                      
            #self.db_s = self.db_s.drop_duplicates().sort_index()    #重複行があれば削除する & 日付が古い順番にデータを並べ替える
            self.db_s = self.db_s.drop_duplicates()    #重複行があれば削除する (sort_index()はエラーが出るため削除)
            #print("d1")    
            #print("self.db_s gb")
            #print(self.db_s)

        except AttributeError: 
            self.db_s=self.add_db_s


        #print("self.db_s")         
        #print(self.db_s)    



        self.db_s.to_csv(setting.HOME_PATH + str(stock_num) + ".csv",header=True) #headerなしでcsvファイルに書き出し
        return self.db_s
Пример #27
0
    def __init__(self, corp_cd, start_date, end_date):
        q = jsm.Quotes()
        self.corp_cd = corp_cd
        self.start_date = start_date
        self.end_date = end_date
        self.close_dict = {}
        self.pricedata = q.get_historical_prices(corp_cd, jsm.DAILY,
                                                 start_date, end_date)
        self.close_list = []
        self.date_list = []

        for pricedata_eachday in self.pricedata:
            self.close_dict[str(pricedata_eachday.date).replace(
                ' 00:00:00', '')] = pricedata_eachday.close

        for k, v in sorted(self.close_dict.items()):
            self.close_list.append(v)
            self.date_list.append(k)
Пример #28
0
def main():
    con = mysql.connector.connect(host=config.db['host'],
                                  db=config.db['db'],
                                  user=config.db['user'],
                                  passwd=config.db['passwd'])

    cur = con.cursor()

    q = jsm.Quotes()

    dt = datetime.date
    start_date = dt.today() - datetime.timedelta(days=3)
    end_date = dt.today() - datetime.timedelta(days=1)

    cur.execute("SELECT ccode FROM brands")
    res = cur.fetchall()
    for r in res:
        try:
            data = q.get_historical_prices(r[0],
                                           jsm.DAILY,
                                           start_date=start_date,
                                           end_date=end_date)
            ts = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")

            for d in data:
                try:
                    cur.execute(
                        "INSERT IGNORE INTO prices(ccode, date, open, high, low, close, volume, created_at, updated_at) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                        [
                            r[0], d.date, d.open, d.high, d.low, d.close,
                            d.volume, ts, ts
                        ])
                    con.commit()
                except:
                    pass
        except:
            pass

    cur.close()
    con.close()
Пример #29
0
def main():
    con = mysql.connect(host=config.db['host'],
                        db=config.db['db'],
                        user=config.db['user'],
                        passwd=config.db['passwd'],
                        charset='utf8')
    cur = con.cursor(dictionary=True, buffered=True)

    q = jsm.Quotes()

    cur.execute("SELECT ccode FROM brands")
    res = cur.fetchall()
    for r in res:
        try:
            finance_data = q.get_finance(r['ccode'])

            market_cap = finance_data.market_cap
            shares_issued = finance_data.shares_issued
            dividend_yield = finance_data.dividend_yield
            dividend_one = finance_data.dividend_one
            per = finance_data.per
            pbr = finance_data.pbr
            eps = finance_data.eps
            bps = finance_data.bps
            price_min = finance_data.price_min
            round_lot = finance_data.round_lot

            ts = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
            cur.execute(
                "INSERT INTO finances(ccode, market_cap, shares_issued, dividend_yield, dividend_one, per, pbr, eps, bps, price_min, round_lot, created_at, updated_at) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, '%s', '%s') ON DUPLICATE KEY UPDATE market_cap = %s, shares_issued = %s, dividend_yield = %s, dividend_one = %s, per = %s, pbr = %s, eps = %s, bps = %s, price_min = %s, round_lot = %s, updated_at = '%s'"
                % (r['ccode'], market_cap, shares_issued, dividend_yield,
                   dividend_one, per, pbr, eps, bps, price_min, round_lot, ts,
                   ts, market_cap, shares_issued, dividend_yield, dividend_one,
                   per, pbr, eps, bps, price_min, round_lot, ts))
            con.commit()
        except:
            pass

    cur.close()
    con.close()
Пример #30
0
def returnList(list):
    industries = {
        '0050': "農林・水産業",
        '1050': "鉱業",
        '2050': "建設業",
        '3050': "食料品",
        '3100': "繊維製品",
        '3150': "パルプ・紙",
        '3200': "化学",
        '3250': "医薬品",
        '3300': "石油・石炭製品",
        '3350': "ゴム製品",
        '3400': "ガラス・土石製品",
        '3450': "鉄鋼",
        '3500': "非鉄金属",
        '3550': "金属製品",
        '3600': "機械",
        '3650': "電気機器",
        '3700': "輸送機器",
        '3750': "精密機器",
        '3800': "その他製品",
        '4050': "電気・ガス業",
        '5050': "陸運業",
        '5100': "海運業",
        '5150': "空運業",
        '5200': "倉庫・運輸関連業",
        '5250': "情報・通信",
        '6050': "卸売業",
        '6100': "小売業",
        '7050': "銀行業",
        '7100': "証券業",
        '7150': "保険業",
        '7200': "その他金融業",
        '8050': "不動産業",
        '9050': "サービス業"
    }
    ind = industries[str(list)]
    rowdata = jsm.Quotes().get_brand(str(list))
    return template('list', list=list, ind=ind, rowdata=rowdata)