Esempio n. 1
0
def uploadFile():
    form = request.form.to_dict()
    id = form.get('id')
    print('上传接受的参数', form)
    print('接收信息', request.files)
    file = request.files['file']
    print('file', type(file), file)
    print('文件名', file.filename)  # 打印文件名
    print('name', file.name)
    f = file.read()  # 文件内容
    data = xlrd.open_workbook(file_contents=f)
    table = data.sheets()[0]
    names = data.sheet_names()  # 返回book中所有工作表的名字

    status = data.sheet_loaded(names[0])  # 检查sheet1是否导入完毕
    print('导入状态', status)
    nrows = table.nrows  # 获取该sheet中的有效行数
    ncols = table.ncols  # 获取该sheet中的有效列数
    # print('nrows',nrows)
    # print('ncols',ncols)
    s = table.col_values(2)  # 第1列数据
    print('尺码', s)
    table_name = names[0]
    Batch.update(id=id, upload=1, excel_name=form.get('excel_name'))
    Stock.delete_by_batch_id(id=id)
    res = formatExcel(table)
    # 根据文件名添加批次
    for r in res:
        r['batch'] = form.get('id')

    r = Stock.add_by_list(res)
    # print('导入结果', r)
    return make_response(jsonify(Res.success(r)))
Esempio n. 2
0
def restock(inv_id):
    if request.method == 'POST':
        qty = request.form['qty']
        r = Stock(quantity=qty, inventoryId=inv_id)
        r.create_record()
        flash('New stock successfully added!', 'success')

    return redirect(url_for('inventories'))
def populate_stock_real_time():
    try:
        stocks_prices = get_stocks_real_time([stock.ticker for stock in Stock.all()])
    except:
        return
    for stock_price in stocks_prices:
        stock = Stock.where('ticker', stock_price['ticker']).first()
        if stock:
            stock.hourly_quotes().save(HourlyQuote(stock_price['info']))
Esempio n. 4
0
def add_stock(id):

    if request.method == 'POST':

        stock = request.form['stock']

        new_stock = Stock(inv_id=id, stock=stock)
        new_stock.create_record()
        return redirect(url_for('inventories'))
 def load_df(self, investment_id):
     stock = Stock(self.mysql_obj)
     stock_data = stock.get_all_by_investment_id(investment_id)
     if stock_data and len(stock_data) > 60:
         df = pd.DataFrame(stock_data)
         df.columns = ['high', 'low', 'adjusted_close', 'date']
         df.set_index('date', inplace=True)
         df.dropna()
         self.stocks = df.sort_index(ascending=True)
Esempio n. 6
0
def index():
    stocks = Stock.get_all_stocks()
    total = Stock.get_total()
    form = AddStockForm()
    return render_template('stocks/index.html',
                           stocks=stocks,
                           Stock=Stock,
                           total=total,
                           form=form)
Esempio n. 7
0
 def add_past_values_to_df(self):
     latest_date = self.df['date'].unique()[0]
     past_date = get_past_latest_week_day(latest_date)
     stock = Stock(self.mysql_obj)
     stocks = stock.get_close_adjusted_and_investment_id(past_date)
     for s in stocks:
         self.df.loc[self.df['investment_id'] == s[1],
                     'past_date'] = past_date
         self.df.loc[self.df['investment_id'] == s[1],
                     'past_adjusted_close'] = s[0]
Esempio n. 8
0
def create_stock_from_products():
    all_products = product_repository.select_all()
    choices = range(0,30)
    
    for product in all_products:
        item_to_stock = Stock(product)
        random_number = random.choice(choices)
        item_to_stock.modify_count(random_number)

        stock_repository.save(item_to_stock)
Esempio n. 9
0
def populate_stock_real_time():
    try:
        stocks_prices = get_stocks_real_time(
            [stock.ticker for stock in Stock.all()])
    except:
        return
    for stock_price in stocks_prices:
        stock = Stock.where('ticker', stock_price['ticker']).first()
        if stock:
            stock.hourly_quotes().save(HourlyQuote(stock_price['info']))
def stock(manufacturer):
    stock = []

    sql = "SELECT * FROM stock WHERE manufacturer_id = %s"
    values = [manufacturer.id]
    results = run_sql(sql, values)
    for row in results:
        stock = Stock(row['name'], row['description'], row['manufacturer'],
                      row['cost'], row['price'], row['id'])
        stock.append(stock)
    return stock
Esempio n. 11
0
 def create_df(self):
     stock = Stock(self.mysql_obj)
     investment = Investment(self.mysql_obj)
     stocks = stock.get_all_latest()
     columns = ('adjusted_close', 'date', 'investment_id')
     df = pd.DataFrame(stocks, columns=columns)
     investments_ids = tuple(df['investment_id'].unique())
     investments = investment.get_all_by_ids(investments_ids)
     for inv in investments:
         df.loc[df['investment_id'] == inv[0], 'investment_name'] = inv[1]
     self.df = df
Esempio n. 12
0
def run():
    req = urllib2.Request('ftp://115.29.204.48/webdata/ashare_perf.txt')
    response = urllib2.urlopen(req)

    for line in response:
        if not line or '|' not in line:
            continue
        line = map(lambda x: x.strip(), line.split('|'))
        if not line[1]:
            continue

        try:
            stock = Stock(
                code=line[1],
                date=datetime.datetime.strptime(line[0], '%Y%m%d'),
                open=float(line[2] or 0),
                close=float(line[5] or 0),
                high=float(line[3] or 0),
                low=float(line[4] or 0),
                change=float(line[6] or 0),
                change_rate=float(line[7] or 0),
                volume=int(line[8] or 0),
                turnover=int(line[9] or 0),
                market_cap=line[10],
                cons_num=line[11],
                p_e1=line[12],
                p_e2=line[13],
                d_p1=line[14],
                d_p2=line[15],
                open_interest=line[16] or 0,
                settlement_turnover=line[17] or 0,
                modified_duration=line[18] or 0,
                convexity=line[19] or 0,
                yield_to_maturity=line[20] or 0,
                duration=line[21] or 0,
                average_price=line[22] or 0,
                net_price=line[23] or 0,
                interest_reinvestment_price=line[24] or 0,
                reserve=line[25] or 0,
                created_at=datetime.datetime.now()
            )
        except ValueError:
            print line
            raise

        try:
            stock.save()
        except (IntegrityError, InvalidRequestError):
            continue
Esempio n. 13
0
def populate_stock_real_time():
    try:
        stocks_prices = get_stocks_real_time([stock.ticker for stock in Stock.all()])
    except:
        try:
            stocks_prices = scrape_yahoo_site([stock.ticker for stock in Stock.all()])
        except:
            try:
                stocks_prices = get_stocks_real_time_google([stock.ticker for stock in Stock.all()])
            except:
                return
    for stock_price in stocks_prices:
        stock = Stock.where('ticker', stock_price['ticker']).first()
        if stock:
            stock_price['info']['stock_id'] = stock.id
            HalfHourlyQuote(stock_price['info']).save()
Esempio n. 14
0
def uploadFile():

    print('接收信息', request.files)
    file = request.files['file']
    print('file', type(file), file)
    print('文件名', file.filename)  # 打印文件名
    print('name', file.name)
    f = file.read()  # 文件内容
    data = xlrd.open_workbook(file_contents=f)
    table = data.sheepts()[0]
    names = data.sheet_names()  # 返回book中所有工作表的名字

    status = data.sheet_loaded(names[0])  # 检查sheet1是否导入完毕
    print('导入状态', status)
    nrows = table.nrows  # 获取该sheet中的有效行数
    ncols = table.ncols  # 获取该sheet中的有效列数
    # print('nrows',nrows)
    # print('ncols',ncols)
    s = table.col_values(2)  # 第1列数据
    print('尺码', s)
    table_name = names[0]
    res = formatExcel(table)
    # 根据文件名添加批次
    for r in res:
        r['batch'] = table_name

    r = Stock.add_by_list(res)
    # print('导入结果', r)
    return make_response(jsonify(Res.success(r)))
Esempio n. 15
0
def add_stock():
    if request.method == 'POST':
        stock_symbol = request.form['stock_symbol']
        num_of_shares = request.form['num_of_shares']
        purchase_price = request.form['purchase_price']
        Stock(stock_symbol, num_of_shares, purchase_price).save_to_mongo()
        return redirect(url_for('stocks.index'))
Esempio n. 16
0
def update():
    form = request.form.to_dict()
    form['editor'] = session.get('id')
    data = Stock.update(**form)
    print('data', data)
    r = Res.success(data)
    return make_response(jsonify(r))
Esempio n. 17
0
def update_basket(id):
    stock_item = stock_repository.select(id)
    new_basket = request.form["newBasketCount"]
    new_stock_item = Stock(stock_item.product, stock_item.count1, new_basket,
                           id)
    stock_repository.update(new_stock_item)
    return redirect("/basket")
Esempio n. 18
0
def add_10_to_basket(id):
    stock_item = stock_repository.select(id)
    new_basket = stock_item.basket + 10
    new_stock_item = Stock(stock_item.product, stock_item.count1, new_basket,
                           id)
    stock_repository.update(new_stock_item)
    return redirect("/")
Esempio n. 19
0
def func():
    """
    20000101 - 2019年12月31号,日线的总数据量
    :return:
    """
    db_res = TradeCal.select(TradeCal.cal_date).where(
        TradeCal.is_open == 1).order_by(TradeCal.cal_date)
    l = len(db_res)
    d = dict()
    for i, x in enumerate(db_res):
        the_day = int(x.cal_date)
        d[the_day] = i + 1

    end = d[20191231]
    result = []
    # db_res = Stock.select(Stock.list_date).where(Stock.list_status == 'L')
    db_res = Stock.query_focus_stocks()
    for x in db_res:
        the_day = int(x.list_date)
        if the_day <= 20000104:
            the_day = 20000104
        # if the_day <= 20140102:
        #     the_day = 20140102

        start = d[the_day]
        result.append(end - start)

    print sum(result)
Esempio n. 20
0
    def __next__(self):
        p_info_event = super().__next__

        p_info_stock = ProvidableInfo()
        p_info_stock.type = Stock
        p_info_stock.idAtProviders = p_info_event.idAtProviders
        p_info_stock.dateModifiedAtProvider = p_info_event.dateModifiedAtProvider

        return p_info_event, p_info_stock

        event.venue = self.venue
        stock = Stock()
        stock.idAtProvider = event.idAtProvider
        stock.dateModifiedAtProvider = event.dateModifiedAtProvider
        stock.event = event
        return stock
Esempio n. 21
0
def queryByBatch():
    # 查询商品大类
    form = request.form.to_dict()
    id = form.get('id')
    r = Stock.queryAll(id=id)
    r = Res.success(r)
    print('查询所有商品', r)
    return make_response(jsonify(r))
Esempio n. 22
0
 def getAllStocks(self):
     dao = StocksDAO()
     stocks_list = dao.getAllStocks()
     result_list = []
     for row in stocks_list:
         result = Stock().build_dict_from_row(row)
         result_list.append(result)
     return jsonify(result_list)
Esempio n. 23
0
 def getStockById(self, rid, sid):
     dao = StocksDAO()
     row = dao.getStockById(rid, sid)
     if not row:
         return jsonify(Error="Stock Not Found"), 404
     else:
         stock = Stock().build_dict_from_row(row)
         return jsonify(stock)
Esempio n. 24
0
def delete():
    form = request.form.to_dict()
    id = form.get('id')
    r = Stock.delete_by_batch_id(id=id)
    r = Batch.delete_by_ids(id)
    r = Batch.all()
    print('删除', r)
    return make_response(jsonify(r))
Esempio n. 25
0
 def getSumOfResources(self):
     dao = StocksDAO()
     sum_list = dao.getSumOfResources()
     result_list = []
     for row in sum_list:
         result = Stock().build_dict_from_row_sum(row)
         result_list.append(result)
     return jsonify(result_list)
Esempio n. 26
0
    def __return_stocks_from_environ(self):
        stocks = os.environ['STOCKS'].split(',')

        result = []

        for stock in stocks:
            result.append(Stock(stock, None))

        return result
Esempio n. 27
0
def get_all_stocks():
    source = requests.get(ALL_STOCKS_URL).text
    soup = BeautifulSoup(source, 'html5lib')
    data_table = soup.find('table', class_='pcq_tbl MT10')
    rows = data_table.find_all('td')
    for row in rows:
        title = row.find('a').text
        href = row.find('a', href=True)['href']
        all_stocks.append(Stock(title, href))
Esempio n. 28
0
def add_stock(inv_id):
    if request.method == 'POST':
        stock = request.form['stock']
        print(inv_id)
        stock = Stock(inv_id=inv_id, stock=stock)
        db.session.add(stock)
        db.session.commit()

    return redirect(url_for('inventories'))
Esempio n. 29
0
def select(id):
    stock = None
    sql = "SELECT * FROM stock WHERE id = %s"
    values = [id]
    result = run_sql(sql, values)[0]

    if result is not None:
       manufacturer = manufacturer_repository.select(result['manufacturer_id']) 
       stock = Stock(result['name'], result['description'], manufacturer, result['cost'] ,result['price'], result['in_stock'], result['id'])
    return stock
Esempio n. 30
0
def select(id):
    sql = "SELECT * FROM stock WHERE id = %s"
    values = [id]
    result = run_sql(sql, values)[0]
    if result is not None:
        product = product_repository.select(result["product_id"])
        the_stock = Stock(product, result["count1"], result["basket"],
                          result["id"])

    return the_stock
Esempio n. 31
0
def update_stock(id):
    name = request.form['name']
    description = request.form['description']
    price = int(request.form['price'])
    cost = int(request.form['cost'])
    in_stock = request.form['in_stock']
    manufacturer = manufacturer_repository.select(
        request.form['manufacturer_id'])
    stock = Stock(name, description, manufacturer, cost, price, in_stock, id)
    stock_repository.update(stock)
    return redirect('/stock')
Esempio n. 32
0
def sell_stock(id):
    stock_item = stock_repository.select(id)
    name = stock_item.name
    description = stock_item.description
    price = stock_item.price
    cost = stock_item.cost
    in_stock = False
    manufacturer = manufacturer_repository.select(stock_item.manufacturer.id)
    stock = Stock(name, description, manufacturer, cost, price, in_stock, id)
    stock_repository.update(stock)
    return redirect('/stock')
def populate_stock_history(beg, end):
    for stock in Stock.all():
        try: 
            stock_history = get_stock_history(stock.ticker, BEG, END)
        except:
            print('ERROR: could not get stock history for \n {}'.format(stock.ticker))
            print(sys.exc_info())
            continue
        for day in stock_history:
            try:
                stock_quotes = stock.daily_quotes()
            except:
                print('ERROR: could not get stocks for \n {}'.format(stock.ticker))
                raise sys.exc_info()
            if not stock_quotes.save(DailyQuote(day)):
                print('ERROR: could not save daily quote for \n {}'.format(day))
def populate_single_stock_history(ticker):
    stock = Stock.where('ticker', ticker).first()