Example #1
0
def save_stocks(all_stocks):
    """save all stocks (names, symbol, women_lead etc.. ) in the database from AA API  """
    women_lead = [
        'GM', 'BBY', 'ANTM', 'HSY', 'VTR', 'ORCL', 'TPR', 'ULTA', 'NDAQ',
        'DUK', 'PGR', 'OXY', 'BEN', 'SYF', 'VRTX', 'CDW', 'CUS', 'OTIS', 'REG',
        'ZTS', 'CLX', 'ROST', 'CE', 'AMD', 'ACN', 'GPS', 'UPS', 'ANET', 'NOC'
    ]

    count = 0
    for stock in all_stocks:
        print(stock)
        if count != 0:
            if stock[0] in women_lead:
                stockInfo = Stock(symbol=stock[0],
                                  stock_name=stock[1],
                                  exchange=stock[2],
                                  asset_type=stock[3],
                                  status=[4],
                                  ipo_date=stock[5],
                                  delisting_date=stock[6],
                                  women_lead=True)
            else:
                stockInfo = Stock(symbol=stock[0],
                                  stock_name=stock[1],
                                  exchange=stock[2],
                                  asset_type=stock[3],
                                  status=[4],
                                  ipo_date=stock[5],
                                  delisting_date=stock[6])

            db.session.add(stockInfo)
            db.session.commit()
        count += 1

    return "Finished"
Example #2
0
def run():
    from cqlengine import connection

    connection.setup(['127.0.0.1'], "cqlengine")

    from cqlengine import management

    management.drop_table(Stock)
    management.sync_table(Stock)

    Stock.create(name="WPRO", prices={
        datetime.date(2014, 12, 1): 200
        , datetime.date(2014, 12, 2): 220.45
        , datetime.date(2014, 12, 3): 250.67
        , datetime.date(2014, 12, 4): 246.86
        , datetime.date(2014, 12, 5): 201
        , datetime.date(2014, 12, 6): 233
        , datetime.date(2014, 12, 7): 245
        , datetime.date(2014, 12, 8): 300
        , datetime.date(2014, 12, 9): 307
        , datetime.date(2014, 12, 10): 180
        , datetime.date(2014, 12, 11): 405
        , datetime.date(2014, 12, 12): 400
        , datetime.date(2014, 12, 13): 670
        , datetime.date(2014, 12, 14): 260
        , datetime.date(2014, 12, 15): 250
        , datetime.date(2014, 12, 16): 251
        , datetime.date(2014, 12, 17): 254
        , datetime.date(2014, 12, 18): 267
        , datetime.date(2014, 12, 19): 270
    }, events={
        datetime.date(2014, 12, 13): "Something happened over here",
        datetime.date(2014, 12, 19): "The bears are playing"
    })

    Stock.create(name="INFY", prices={
        datetime.date(2014, 8, 1): 3200
        , datetime.date(2014, 8, 2): 3220.45
        , datetime.date(2014, 8, 3): 3250.67
        , datetime.date(2014, 8, 4): 3246.86
        , datetime.date(2014, 8, 5): 3201
        , datetime.date(2014, 8, 6): 3233
        , datetime.date(2014, 8, 7): 3245
        , datetime.date(2014, 8, 8): 3300
        , datetime.date(2014, 8, 9): 3307
        , datetime.date(2014, 8, 10): 3180
        , datetime.date(2014, 8, 11): 3405
        , datetime.date(2014, 8, 12): 3400
        , datetime.date(2014, 8, 13): 3670
        , datetime.date(2014, 8, 14): 3260
        , datetime.date(2014, 8, 15): 3250
        , datetime.date(2014, 8, 16): 3251
        , datetime.date(2014, 8, 17): 3254
        , datetime.date(2014, 8, 18): 3267
        , datetime.date(2014, 8, 19): 3270
    })
Example #3
0
 def AlarmeMedicamentos(self, idFarmacia):
     with self.lock:
         listStock = self.DB.SelectStock(idFarmacia)
         for s in listStock:
             if s.quantidade < 4:
                 rec = Stock(s.idFarm, s.nome, s.quantidade)
                 self.DB.InsertAlarme(idFarmacia, rec)
Example #4
0
def create_stock(ticker, exchange, assetType, priceCurrency, startDate,
                 endDate):
    stock = Stock(ticker=ticker,
                  exchange=exchange,
                  assetType=assetType,
                  priceCurrency=priceCurrency,
                  startDate=startDate,
                  endDate=endDate)
    db.session.add(stock)
    db.session.commit()
    return stock
Example #5
0
    def UpdateStock(self, idFarmacia, nomeMedic, quantidade):
        stockRec = self.SearchMedicamentoInStock(idFarmacia, nomeMedic)
        if stockRec == None:
            rec = Stock(idFarmacia, nomeMedic, quantidade)
            self.DB.InsertStock(idFarmacia, rec)
        else:
            stockRec.condition.acquire()
            stockRec.quantidade += quantidade
            stockRec.condition.notify_all()
            stockRec.condition.release()

        return 1
Example #6
0
def portfolio_json():
    """JSONify the user's stock portfolio."""
    # alluserstocks = StockUser.query.filter_by(user_id=session.get("user_id")).all()
    # jsonlist=[]
    # for userstock in alluserstocks:
    #     jsonlist.append(userstock.json())
    # data = {"children":jsonlist,"name":"stockidentifier"}
    # print data
    # import pdb;pdb.set_trace()
    data=Stock.clusternester(session.get("user_id"))
    # outerdata = {"children": data, "name": "stockidentifier"}
    return jsonify(data)
Example #7
0
def getStocksByKey(keyword):
    result = []
    try:
        conn = sqlite3.connect(DB_NAME)
        # print("getStocks connect db successfully")
        cur = conn.cursor()
        cur.execute("select * from stock where name like ? or code=?",('%'+keyword+'%',keyword,))
        items = cur.fetchall()
        for item in items:
            stock = Stock()
            stock.code = item[0]
            stock.name = item[1]
            stock.prefix = item[2]
            result.append(stock)
    except Exception as e:
        currentLogger.error("%s",e)
    finally:
        if cur!=None:
            cur.close()
        if conn!=None:
            conn.close()
    return result
Example #8
0
def save_stock_list(stock_list):
    session = DBSession()

    for stock in stock_list:
        symbol = stock["symbol"]
        name = stock["name"]
        stock_model = Stock(symbol, name)
        session.add(stock_model)

    session.commit()
    session.close()

    return True
Example #9
0
def create_stock(symbol, name, description, industry, asset_type, currency,
                 employees):

    stock = Stock(symbol=symbol,
                  name=name,
                  description=description,
                  industry=industry,
                  asset_type=asset_type,
                  currency=currency,
                  employees=employees)
    db.session.add(stock)
    db.session.commit()

    return stock
Example #10
0
def add_stock(**kwargs):
    '''
    kwargs = dict{
        'date': str/date
        'ticker': str
        'p_open': float
        'p_close': float
        'volume': float
    }
    '''
    to_add = Stock(date=kwargs['date'],
                   ticker=stock_date['ticker'],
                   p_open=kwargs['p_open'],
                   p_close=kwargs['p_close'],
                   volume=kwargs['volume'])
    db.session.add(to_add)
    db.session.commit()
Example #11
0
    def query_all_stock(self):
        stocks = {}

        data_source = DataSource()
        conn = data_source.get_conn()

        cur = conn.cursor()
        try:
            cur.execute("select id, code, name, bps ,eps ,net_income ,ngpr ,income ,sps ,fps ,udpps ,total_stock_issue,"
                        "liqui from stock order by id")
            result = cur.fetchall()
            for r in result:
                stock = Stock(r[0], r[1], r[2], r[3], r[4], r[5], r[6],
                              r[7], r[8], r[9], r[10], r[11], r[12])
                stocks[r[1]] = stock

            return stocks
        except:
            self.__logger.error("Unexpected error: %s" % sys.exc_value)
            return None
        finally:
            cur.close()
            conn.close()
Example #12
0
                "payout_schedule": row["Payout Schedule"].strip(),
                "stock_price": row["Stock Price"].strip()
            }

with open('data/symbols.csv', 'r') as file:
    csv_file = csv.DictReader(file)
    for row in csv_file:
        symbol = row['Ticker'].strip()
        if symbol in stocks:
            stocks[symbol]["company_name"] = row["Company Name"]
            stocks[symbol]["sector"] = row["Sector"]
            stocks[symbol]["payout_ratio"] = row[
                "Dividend Payout Ratio"].strip()
            stocks[symbol]["dividend_yield"] = row["Dividend Yield"].strip()

for stock in stocks:
    print('stock', stocks[stock])
    ticker = Stock(symbol=stocks[stock]['symbol'],
                   sector=stocks[stock]['sector'],
                   company_name=stocks[stock]['company_name'],
                   dividend_amount=stocks[stock]['dividend_amount'],
                   dividend_yield=stocks[stock]['dividend_yield'],
                   payout_schedule=stocks[stock]['payout_schedule'],
                   payout_ratio=stocks[stock]['payout_ratio'],
                   stock_price=stocks[stock]['stock_price'])

    db.session.add(ticker)
    db.session.commit()

# ***************************************************************************
Example #13
0
#! /usr/bin/env python

import itertools
import functools
import time

from model import Stock, Trade
from service import StockService
from decimal import *

stock_count = itertools.count(1)
trade_count = itertools.count(1)

stock_list = [
    Stock("TEA", "COMMON", 23, 0, 100, stock_count.next()), 
    Stock("POP", "COMMON", 8, 0, 100, stock_count.next()),
    Stock("ALE", "COMMON", 12, 0, 109, stock_count.next()),
    Stock("GIN", "PREFFERED", 23, 2, 100, stock_count.next()),
    Stock("JOE", "COMMON", 13, 0, 250, stock_count.next())
]
symbol_list = [stock.symbol for stock in stock_list]
service = StockService({stock.symbol:stock for stock in stock_list})


def read_stock_symbol():
    """ Reading Stock Symbol from input"""
    symbol = ""
    while(True):
        symbol = raw_input("Enter stock symbol:")
        if(symbol in symbol_list):
            break
Example #14
0
File: main.py Project: zabil/stocky
def by_symbol(symbol):
    return jsonify(trends=[stock.serialize() for stock in Stock.objects(Stock.name == symbol).allow_filtering()])
Example #15
0
            daily.turnover = item[30]
            result.append(daily)
    except Exception as e:
        currentLogger.error("%s",e)
    finally:
        if cur!=None:
            cur.close()
        if conn!=None:
            conn.close()
    return result[::-1]

if __name__ == "__main__":

    from model import Stock, Daily

    stock = Stock()
    stock.name = "美的集团"
    stock.code = "000333"
    stock.prefix = "sz"
    insertStock(stock)

    daily = Daily()
    daily.code = "000333"
    daily.date = "2021-02-10"
    daily.open = "102.9"
    daily.last_close = "101.7"
    daily.current = "107.2"
    daily.high = "108"
    daily.low = "101.5"
    daily.quantity = "8654778686"
    daily.amount = "1545678968498786.01"
Example #16
0
from sys import argv
from model import Stock, Exchange, Company
from config import DBURL
import pandas as pd
from sqlalchemy.orm import sessionmaker, relation, backref
from sqlalchemy import create_engine
script, filename = argv
#filename = 'data/stock.csv'

engine = create_engine(DBURL)

Session = sessionmaker(bind = engine)

session = Session()

data = pd.read_csv(filename, sep=',', header=0)


for i in range(0,len(data)):
    code = data['key'][i]
    session.add(Stock(code))

session.commit()
Example #17
0
import sqlalchemy as sa
from sqlalchemy.orm import Query, scoped_session, sessionmaker
import datetime
from model import Publisher, Book, Shop, Stock, Sale
from engine_session import engine, Session

#################### setup some data ######################
pub1 = Publisher(name='МИФ')
sa.session.add(pub1)
sa.session.commit()

book1 = Book(title='45 татуировок менеджера', id_publisher=0)
sa.session.add(book1)
sa.session.commit()

sh1 = Shop(name='Буквоед-1')
sa.session.add(sh1)
sa.session.commit()

st1 = Stock(id_book=0, id_shop=0, count=100)
sa.session.add(st1)
sa.session.commit()

sale1 = Sale(price=570, date_sale=datetime.today(), id_stock=0, count=84)
sa.session.add(sale1)
sa.session.commit()
Example #18
0
 def callback(self, ch, method, properties, body: bytes) -> None:
     stock = Stock()
     session.add(stock)
     session.commit()
     print(" [x] Received %r" % body.decode('utf8'))