def portfolio_add_stock(request, portfolio_id, portfolio, symbol, stock):
    if stock is None:
        stock = Stock(yahoo_symbol=symbol)
        stock.save()
    portfolio.stocks.add(stock)
    portfolio.save()
    return HttpResponse('')
Exemple #2
0
def update_symbols():
    """
    update the symbol list calling myinvestorshub.com
    """
    from finance_game.models import Stock

    def get_countries():
        url = "http://www.myinvestorshub.com/yahoo_stock_list.php"
        countries_html = urllib2.urlopen(url).read()
        index_root = lxml.html.fromstring(countries_html)
        for country in index_root.cssselect("option"):
            yield country.text

    symbol_url_base = "http://www.myinvestorshub.com/yahoo_list.php"
    for country in get_countries():
        if country == "United Kingdom":
            data = urllib.urlencode({"cnt": country})
            binary_data = data.encode('utf-8')
            request = urllib2.Request(symbol_url_base, binary_data)
            response = urllib2.urlopen(request)
            index_root = lxml.html.fromstring(response.read().decode('utf-8'))
            table = index_root.cssselect("table")[3]
            stock_rows = table.cssselect("tr")
            for stock_row in stock_rows[1:]:
                _, company_name, symbol, exchange, country = list(map(lambda s: s.text, stock_row.cssselect("td")))
                if company_name and symbol and exchange and country:
                    print(company_name, symbol, exchange, country)
                    stock = Stock(name=company_name, symbol=symbol, exchange=exchange, country=country)
                    # stock.update_values()
                    stock.save()
Exemple #3
0
def store_stock(stock, market):
    stock_model = Stock(market=market,
                        url=stock['url'],
                        name=stock['name'],
                        symbol=stock['symbol'])
    stock_model.save()

    print stock['name']
Exemple #4
0
def agregar_stock(detalle, almacen):
  if existe_stock(detalle.producto, almacen):
    stock = Stock.objects.get(producto = detalle.producto, en_almacen = almacen)
    stock.unidades = stock.unidades + detalle.cantidad
    stock.save()
  else:
    stock = Stock(producto = detalle.producto, en_almacen = almacen, unidades = detalle.cantidad)
    stock.save()
Exemple #5
0
def BeginToTrade(request):
    RequestUser = request.user
    RequestGroup = RequestUser.group
    context={
        "form":SearchForm(),
        "sear":True
    }
    if request.method=="POST":
        Post = request.POST.dict()
        if Post.has_key("StockName"):
            StockName=str(Post["StockName"])
        else:
            StockName=""
        if Post.has_key("Volume"):
            Volume=Post["Volume"]
        else:
            Volume=0
        if Post.has_key("TransactionType"):
            TransactionType=Post["TransactionType"]
        else:
            TransactionType=None
        print Post

        context={
            "form":OrderForm(),
            "sear":False
            
            }
        
        stock = Stock.objects.filter(StockName=StockName)
        if len(stock)==0:
            print "123123"
            stock = Stock(StockName=StockName)
            stock.save()
            context["StockData"] = jsonpickle.encode(stock.Get_data())
        else:
             context["StockData"] = jsonpickle.encode(stock[0].Get_data())

        if Volume!="" and TransactionType != None:
            RequestUser.group.UpdateAcount()
            stockprice = stock[0].Get_Price()
            if TransactionType=="buy":
                if RequestUser.group.Cash >= stockprice*float(Volume):
                    RequestGroup.transaction_set.create(TransType = TransactionType,StockOfTrans = stock[0], Volume=Volume, PriceAtTrans=stock[0].Get_Price() )
                    context["mess"] = "Succesfully making transaction"
                else:
                    context["mess"] = "You don't have enough money"
            else:
                asset = RequestUser.group.AllAsset
                if asset[StockName] >= float(Volume):
                    RequestGroup.transaction_set.create(TransType = TransactionType,StockOfTrans = stock[0], Volume=Volume, PriceAtTrans=stock[0].Get_Price() )
                    context["mess"] = "Succesfully making transaction"
                else:
                    context["mess"] = "You don't have enough this stock to sell"
        
    return render(request, "BeginToTrade.html", context)
def stock_summary(request, symbol=None):
    if symbol == None:
        symbol = request.POST['symbol']

    current_stock = Stock()
    stock = Share(symbol)
    current_stock.symbol = symbol.upper()
    current_stock.price = stock.get_price()
    current_stock.change = stock.get_change()
    current_stock.volume = stock.get_volume()
    current_stock.prev_close = stock.get_prev_close()
    current_stock.stock_open = stock.get_open()
    current_stock.avg_daily_volume = stock.get_avg_daily_volume()
    current_stock.stock_exchange = stock.get_stock_exchange()
    current_stock.market_cap = stock.get_market_cap()
    current_stock.book_value = stock.get_book_value()
    current_stock.ebitda = stock.get_ebitda()
    current_stock.dividend_share = stock.get_dividend_share()
    current_stock.dividend_yield = stock.get_dividend_yield()
    current_stock.earnings_share = stock.get_earnings_share()
    current_stock.days_high = stock.get_days_high()
    current_stock.days_low = stock.get_days_low()
    current_stock.year_high = stock.get_year_high()
    current_stock.year_low = stock.get_year_low()
    current_stock.fifty_day_moving_avg = stock.get_50day_moving_avg()
    current_stock.two_hundred_day_moving_avg = stock.get_200day_moving_avg()
    current_stock.price_earnings_ratio = stock.get_price_earnings_ratio()
    current_stock.price_earnings_growth_ratio = stock.get_price_earnings_growth_ratio()
    current_stock.price_sales = stock.get_price_sales()
    current_stock.price_book = stock.get_price_book()
    current_stock.short_ratio = stock.get_short_ratio()

    date_metrics = []
    url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+symbol+'/chartdata;type=quote;range=1y/csv'
    page = urllib2.urlopen(url).read()
    pagebreaks = page.split('\n')
    for line in pagebreaks:
        items = line.split(',')
        if 'Company-Name:' in line:
            current_stock.company_name = line[13:len(line)]
            current_stock.save()
        if 'values' not in items:
            if len(items)==6:
                hd = HistoricalData(
                    stock_id = Stock.objects.get(id=int(current_stock.id)).id,
                    date = items[0][4:6]+'/'+items[0][6:9]+'/'+items[0][0:4],
                    close = items[1][0:(len(items[1])-2)],
                    high = items[2][0:(len(items[2])-2)],
                    price_open = items[3][0:(len(items[3])-2)],
                    low = items[4][0:(len(items[4])-2)],
                    volume = items[5][0:-6]+","+items[5][-6:-3]+","+items[5][-3:len(items[5])])
                hd.save()
                date_metrics.append(hd)
    del date_metrics[0]
    return render(request, "stock_summary.html", {'current_stock': current_stock, 'date_metrics': date_metrics})
Exemple #7
0
def show_stock(request, symbol):
    stks = Stock.objects.filter(symbol=symbol)
    if stks.count() == 0:
        stk = Stock(symbol=symbol, price=0.0)
        stk.save()
    elif stks.count() == 1:
        stk = stks[0]
    else:
        return HttpResponse("%s" % stks.count())
    try:
        ss = stk.history.order_by('date')[0]
    except:
        update(stk)
        ss = stk.history.order_by('date')[0]
    return render_to_response('stock.html', {'stock': stk, 'status': ss})
Exemple #8
0
def stock_add(request):
    from app.remote.stocks import StockHistoryClient
    from app.forms import StockWizardForm
    from app.models import Company, Stock

    if request.method == "POST":
        form = StockWizardForm(request.POST)
        pprint(form.is_valid())
        if form.is_valid():
            # save
            company = Company()
            company.name = form.cleaned_data['company_name']
            company.country = form.cleaned_data['company_country']
            company.save()

            stock = Stock()
            stock.company = company
            stock.name = form.cleaned_data['name']
            stock.wkn = form.cleaned_data['wkn']
            stock.isin = form.cleaned_data['isin']
            stock.symbol = form.cleaned_data['symbol']
            stock.type = form.cleaned_data['type']
            stock.default_stock_exchange = form.cleaned_data['default_stock_exchange']
            stock.save()

            return HttpResponseRedirect(reverse('stock', args=(stock.symbol,)))
        else:
            pprint(form.errors)
    else:
        data = None
        if 'wkn_or_isin' in request.GET:
            shc = StockHistoryClient()
            data = shc.get_basics_by_wkn_or_isin(wkn_or_isin=request.GET['wkn_or_isin'])

            data['company_country'] = data['country']
            data['company_name'] = data['name']

        form = StockWizardForm(initial=data)

    return render_to_response(
        'stock_wizard_add.html',
        {
            'form': form
        },
        context_instance=RequestContext(request)
    )
Exemple #9
0
def stock_add(request):
    from app.remote.stocks import StockHistoryClient
    from app.forms import StockWizardForm
    from app.models import Company, Stock

    if request.method == "POST":
        form = StockWizardForm(request.POST)
        pprint(form.is_valid())
        if form.is_valid():
            # save
            company = Company()
            company.name = form.cleaned_data['company_name']
            company.country = form.cleaned_data['company_country']
            company.save()

            stock = Stock()
            stock.company = company
            stock.name = form.cleaned_data['name']
            stock.wkn = form.cleaned_data['wkn']
            stock.isin = form.cleaned_data['isin']
            stock.symbol = form.cleaned_data['symbol']
            stock.type = form.cleaned_data['type']
            stock.default_stock_exchange = form.cleaned_data[
                'default_stock_exchange']
            stock.save()

            return HttpResponseRedirect(reverse('stock',
                                                args=(stock.symbol, )))
        else:
            pprint(form.errors)
    else:
        data = None
        if 'wkn_or_isin' in request.GET:
            shc = StockHistoryClient()
            data = shc.get_basics_by_wkn_or_isin(
                wkn_or_isin=request.GET['wkn_or_isin'])

            data['company_country'] = data['country']
            data['company_name'] = data['name']

        form = StockWizardForm(initial=data)

    return render_to_response('stock_wizard_add.html', {'form': form},
                              context_instance=RequestContext(request))
Exemple #10
0
def import_data():
    snapshot = Snapshot()
    snapshot.snapshot = datetime.now()
    snapshot.save()

    print "Importing data from finviz"
    r = requests.get('http://finviz.com/export.ashx?v=152', cookies={"screenerUrl": "screener.ashx?v=152&f=cap_smallover&ft=4", "customTable": "0,1,2,6,7,10,11,13,14,45,65"})
    data = csv_to_dicts(r.text)
    tickers = []
    for row in data:
        try:
            stock = Stock()
            stock.snapshot = snapshot
            if row["Ticker"]:
                stock.Ticker = row["Ticker"]
            print stock.Ticker
            tickers.append(stock.Ticker)
            if "Importing " + row["Company"]:
                stock.Company = row["Company"]
            if row["Market Cap"]:
                stock.MarketCap = row["Market Cap"]
            if row["P/E"]:
                stock.PE = row["P/E"]
            if row["P/S"]:
                stock.PS = row["P/S"]
            if row["P/B"]:
                stock.PB = row["P/B"]
            if row["P/Free Cash Flow"]:
                stock.PFreeCashFlow = row["P/Free Cash Flow"] 
            if row["Dividend Yield"]:
                stock.DividendYield = row["Dividend Yield"][:-1]
            if row["Performance (Half Year)"]:
                stock.PerformanceHalfYear = row["Performance (Half Year)"][:-1]
            if row["Price"]:
                stock.Price = row["Price"]
            stock.save()
        except:
            pdb.set_trace()
            

    import_evebitda(snapshot)

    import_buyback_yield(snapshot)
Exemple #11
0
def add(ticker):
  print('add XF')
  try:
    stock = Stock()
    stock['name'] = ticker
    stock['symbol'] = ticker
    try:
      stock['last_price'] = float(stocks.get_quote(ticker))
    except:
      print("lookup failed for %s" % ticker)
    print('presave')
    try:
      stock.save()
    except:
      print('stock failed to save')
    print("Created %s Successfully" % stock['name'])
    return render_template('add.html', ticker=ticker)
  except:
    return render_template('uhoh.html')
Exemple #12
0
    def create(stock, product_id) -> dict:
        """ Create Stock """
        result: dict = {}
        try:
            data = Stock.query.filter_by(product_id=product_id).first()
            if(data is None):
                data = Stock(stock, product_id)
                data.save()
            else :
                print(data)
                data.stock = stock
                data.commit()

            result = {
                'product_id': data.product_id,
                'stock': data.stock,
                'date_created': str(data.date_created),
            }
        except IntegrityError:
            Stock.rollback()
            raise ResourceExists('file_name already exists')

        return result
Exemple #13
0
def api_save_trade_record(request, *, type, occur_date, occur_amount, balance, **kw):
	
	if not type or not type.strip():
		raise APIValueError('type', 'type cannot be empty.')
	if not occur_amount or not occur_amount.strip():
		raise APIValueError('occur_amount', 'occur_amount cannot be empty')

	if 'charge_fee' in kw:
		charge_fee = kw['charge_fee']
	else:
		charge_fee = 0
	if 'stamp_tax' in kw:
		stamp_tax = kw['stamp_tax']
	else:
		stamp_tax = 0
	if 'transfer_fee' in kw:
		transfer_fee = kw['transfer_fee']
	else:
		transfer_fee = 0
	if 'commission' in kw:
		commission = kw['commission']
	else:
		commission = 0
	if 'stock_balance' in kw:
		stock_balance = kw['stock_balance']
	else:
		stock_balance = 0
	if 'stock_code' in kw:
		stock_code = kw['stock_code']
	else:
		stock_code = ''
	if 'deal_num' in kw:
		deal_num = kw['deal_num']
	else:
		deal_num = 0
	if 'deal_price' in kw:
		deal_price = kw['deal_price']
	else:
		deal_price = 0
	stock = Stock(type=type.strip(), occur_date=occur_date, occur_amount=occur_amount, balance=balance, stock_balance=stock_balance, stock_code=stock_code,
		deal_num=deal_num, deal_price=deal_price, stamp_tax=stamp_tax, transfer_fee=transfer_fee, commission=commission, charge_fee=charge_fee)
	yield from stock.save()
	return stock
Exemple #14
0
def transaction(request):

    if request.user.is_authenticated():
        # if this is a POST request we need to process the form data
        if request.method == 'POST':
            # create a form instance and populate it with data from the request:
            form = TransactionForm(request.POST)
            EntryFormSet = formset_factory(EntryForm, extra=10)
            formset = EntryFormSet(request.POST)

            # check whether it's valid:
            if form.is_valid() and formset.is_valid():
                # process the data in form.cleaned_data as required

                in_type = form.cleaned_data['type']
                in_party = form.cleaned_data['party']
                in_description = form.cleaned_data['description']

                # create the transaction
                # todo be careful because there is a DB hit with create, consider using save
                transaction = Transaction.objects.create(transaction_type=in_type,
                                                         transaction_actor=request.user.username,
                                                         transaction_party=in_party,
                                                         transaction_description=in_description)

                # now save the data for each entry in the formset
                new_entries = []

                for entry_form in formset:
                    in_transaction_gkey = transaction
                    in_product = entry_form.cleaned_data.get('product')
                    in_color = entry_form.cleaned_data.get('color')
                    in_quantity = entry_form.cleaned_data.get('quantity')

                    if in_transaction_gkey and in_product and in_color and in_quantity:

                        # Adjust the stock
                        try:
                            product = Product.objects.get(product_name=in_product, product_color=in_color)
                        except Product.DoesNotExist:
                            product = Product(product_name=in_product, product_color=in_color)
                            product.save()
                        try:
                            stk = Stock.objects.get(product_gkey=product)
                        except Stock.DoesNotExist:
                            stk = Stock(product_gkey=product)
                            stk.save()

                        if transaction.transaction_type == 'In':
                            stk.quantity = stk.quantity + in_quantity
                        else:
                            stk.quantity = stk.quantity - in_quantity
                        stk.save()

                        new_entries.append(Entry(transaction_gkey=in_transaction_gkey,
                                                 product_gkey=product,
                                                 quantity=in_quantity))
                        #todo: add try catch
                        #todo: add verification no 2 same product
                        Entry.objects.bulk_create(new_entries)

                # redirect to a new URL:
                return render(request,'mafia/index.html')

        # if a GET (or any other method) we'll create a blank form
        else:
            form = TransactionForm()
            EntryFormSet = formset_factory(EntryForm,extra=10)
            formset = EntryFormSet()
        return render(request, 'mafia/transaction.html',  {'form': form, 'formset': formset})
    else:
        return render(request, 'mafia/request_login.html')
Exemple #15
0
import sys, os
import csv
#from backtester import settings
from models import Stock
from django.conf import settings
os.environ['DJANGO_SETTINGS_MODULE'] = 'backtester.settings'
#settings.configure(DEBUG=True)
sys.path.append(
    "/Users/anitanahar/Desktop/PythonProjects/Firstfinancialproject/backtester"
)
with open(
        "/Users/anitanahar/Desktop/PythonProjects/Firstfinancialproject/backtester/fixedoutput.csv",
        "r") as csv:
    next(csv)  # skip first line
    for line in csv:
        liner = line.split(",")
        stock = Stock()
        stock.ticker = liner[0]
        stock.save()
Exemple #16
0
def info_submit(request):
    rt = '1'
    act = request.POST.get('act')
    if (act == 'del'):
        code = request.POST.get('code').strip()
        jy_id = request.POST.get('jy_id')
        try:
            print 'code=%s' % code
            del_stock = Stock.objects.filter(code=code).filter(jy_id=jy_id)
            for dstock in del_stock:
                del_issueprice = dstock.issueprice
                break
            #print 'del_issueprice=%s'%del_issueprice
            del_stock.delete()
            #同步到mysql
            sync_mysql_by_code(code=code, old_code=code, jy_id=int(jy_id))
            #for notify issueprice change
            result = oracle_connect.execute(
                select([zjjy_hk_ipo.c.issueprice
                        ]).select_from(zjjy_hk_ipo).where(
                            zjjy_hk_ipo.c.code == code).where(
                                zjjy_hk_ipo.c.jy_id == int(jy_id))).fetchall()
            if (len(result) > 0):
                #print 'issueprice=%s,in jy'%result[0].issueprice
                newissueprice = result[0].issueprice
            else:
                #print 'code:%s,jyid:%s is not record in jy'%(code,jy_id)
                newissueprice = ''
            if (newissueprice != '' and newissueprice != del_issueprice):
                notify_issueprice(exchange='HKEX',
                                  code=code,
                                  lclose=float(newissueprice))

        except Exception as e:
            print e
            rt = str(e).replace('\'', '')
        return HttpResponse("<script>parent.del_result('" + rt + "')</script>")
    elif act == 'update' or act == 'add':
        code = request.POST.get('code').strip()
        old_code = request.POST.get('old_code').strip()
        id = request.POST.get('stockid')
        #check whether this is a new code
        if (code != old_code and False == is_zj_new_code(code)):
            return HttpResponse("<script>parent.submit_result('2','" + act +
                                "')</script>")
        #return HttpResponse("<script>parent.submit_result('can submit','"+act+"')</script>")
        if (act == 'update'):
            if (code != old_code and False == is_jy_new_code(code)):
                return HttpResponse("<script>parent.submit_result('3','" +
                                    act + "')</script>")
            try:
                print 'oldcode=%s' % old_code
                stock = Stock.objects.get(code=old_code)

            except Exception as e:
                print e
        else:  #act==add
            stock = Stock()

        stockname = request.POST.get('stockname').strip()
        issuevolplanned = request.POST.get('issuevolplanned').strip()
        issuevolplanned = issuevolplanned.replace(',', '')
        publicnewshareplanned = request.POST.get(
            'publicnewshareplanned').strip()
        publicnewshareplanned = publicnewshareplanned.replace(',', '').strip()
        issuepriceceiling = request.POST.get('issuepriceceiling').strip()
        issuepricefloor = request.POST.get('issuepricefloor').strip()
        tradeunitpriceatceiling = request.POST.get(
            'tradeunitpriceatceiling').strip()
        exchange = request.POST.get('exchange').strip()
        issuetype = request.POST.get('issuetype').strip()
        applystartdate = request.POST.get('applystartdate').strip()
        issueenddate = request.POST.get('issueenddate').strip()
        proposedlistdate = request.POST.get('proposedlistdate').strip()
        datetoaccount = request.POST.get('datetoaccount').strip()
        tradeunit = request.POST.get('tradeunit').strip()
        issueprice = request.POST.get('issueprice').strip()
        marketcode = request.POST.get('marketcode').strip()
        pin_yin = request.POST.get('pin_yin').strip().upper()
        old_issueprice = request.POST.get('old_issueprice').strip()
        jy_id = request.POST.get('jy_id').strip()
        try:
            stock.code = code
            stock.name = stockname
            if (issuevolplanned != ''):
                stock.issuevolplanned = issuevolplanned
            else:
                stock.issuevolplanned = None
            if (publicnewshareplanned != ''):
                stock.publicnewshareplanned = publicnewshareplanned
            else:
                stock.publicnewshareplanned = None
            if (issuepriceceiling != ''):
                stock.issuepriceceiling = issuepriceceiling
            else:
                stock.issuepriceceiling = None
            if (issuepricefloor != ''):
                stock.issuepricefloor = issuepricefloor
            else:
                stock.issuepricefloor = None
            if (tradeunitpriceatceiling != ''):
                stock.tradeunitpriceatceiling = tradeunitpriceatceiling
            else:
                stock.tradeunitpriceatceiling = None
            stock.exchange = exchange
            stock.issuetype = issuetype
            stock.applystartdate = applystartdate
            stock.issueenddate = issueenddate
            if (proposedlistdate != ''):
                stock.proposedlistdate = proposedlistdate
            else:
                stock.proposedlistdate = None
            if (datetoaccount != ''):
                stock.datetoaccount = datetoaccount
            else:
                stock.datetoaccount = None
            if (tradeunit != ''):
                stock.tradeunit = tradeunit
            else:
                stock.tradeunit = None
            if (issueprice != ''):
                stock.issueprice = issueprice
            else:
                stock.issueprice = None
            stock.marketcode = marketcode
            stock.pin_yin = pin_yin
            if (jy_id != ''):
                stock.jy_id = jy_id
                ijy_id = int(jy_id)
            else:
                ijy_id = 0
            stock.save()
            id = stock.id
            print 'id=%d' % id
            #se='select * from nls_session_parameters'
            #print oracle_connect.execute(se).fetchall()

            if (old_issueprice != issueprice):
                if (issueprice == ''):  #修改了发行价为空
                    issueprice = '0'
                print("use redis interface")
                notify_issueprice(exchange='HKEX',
                                  code=code,
                                  lclose=float(issueprice))
            #同步到 mysql
            print 'code=%s' % code

            sync_mysql_by_code(code=code, old_code=old_code, jy_id=ijy_id)
        except Exception as e:
            print e
            rt = str(e).replace("'", "")
        return HttpResponse("<script>parent.submit_result('" + rt + "','" +
                            act + "')</script>")
    elif (act == 'sync_data'):
        try:
            add_count = 0
            rt = sync_database(calltype='django')
        except Exception as e:
            rt = str(e).replace("'", "")
            #print rt
        print "rt=%s" % (rt)
        return HttpResponse("<script>parent.sync_result('" + str(rt) + "','" +
                            str(add_count) + "')</script>")
    else:  #处理get的情况
        act = request.GET.get('act')
        if (act == 'set_issueprice'):  #在列表页填issueprice
            code = request.GET.get('code')
            jy_id = request.GET.get('jy_id')
            issueprice = request.GET.get('issueprice_' + code + '_' +
                                         jy_id).strip()
            old_issueprice = request.GET.get('old_issueprice_' + code + '_' +
                                             jy_id).strip()
            source = request.GET.get('source')
            try:
                if (source == 'ZJ'):
                    stock = Stock.objects.get(code=code)
                    stock.issueprice = issueprice
                    stock.save()
                elif (source == 'JY'):
                    stock = Stock()
                    ipo = oracle_connect.execute(zjjy_hk_ipo.select().where(
                        zjjy_hk_ipo.c.code == code).where(
                            zjjy_hk_ipo.c.jy_id == jy_id)).first()
                    stock.name = ipo.name
                    stock.code = ipo.code
                    if (ipo.issuevolplanned):
                        stock.issuevolplanned = ipo.issuevolplanned
                    if (ipo.publicnewshareplanned):
                        stock.publicnewshareplanned = ipo.publicnewshareplanned
                    if (ipo.issuepriceceiling):
                        stock.issuepriceceiling = ipo.issuepriceceiling
                    if (ipo.issuepricefloor):
                        stock.issuepricefloor = ipo.issuepricefloor
                    if (ipo.tradeunitpriceatceiling):
                        stock.tradeunitpriceatceiling = ipo.tradeunitpriceatceiling
                    stock.exchange = ipo.exchange
                    stock.issuetype = ipo.issuetype
                    stock.applystartdate = ipo.applystartdate.strftime(
                        '%Y-%m-%d')
                    stock.issueenddate = ipo.issueenddate.strftime('%Y-%m-%d')
                    if (ipo.proposedlistdate):
                        stock.proposedlistdate = ipo.proposedlistdate.strftime(
                            '%Y-%m-%d')
                    if (ipo.datetoaccount):
                        stock.datetoaccount = ipo.datetoaccount.strftime(
                            '%Y-%m-%d')
                    if (ipo.tradeunit):
                        stock.tradeunit = ipo.tradeunit
                    stock.marketcode = ipo.marketcode
                    if (ipo.pin_yin):
                        stock.pin_yin = ipo.pin_yin
                    stock.issueprice = issueprice
                    stock.jy_id = jy_id
                    stock.save()

                #use redis interface
                if (issueprice != '' and old_issueprice != issueprice):
                    notify_issueprice(exchange='HKEX',
                                      code=code,
                                      lclose=float(issueprice))
                #save to mysql
                sync_mysql_by_code(code=code, old_code=code, jy_id=int(jy_id))
            except Exception as e:
                str(e).replace("'", "")

            return HttpResponse("<script>parent.set_issuprice_result('" + rt +
                                "','" + code + "','" + jy_id + "','" +
                                issueprice + "')</script>")
Exemple #17
0
def store_stock(stock, market):
    stock_model = Stock(market=market, url=stock['url'], name=stock['name'], symbol=stock['symbol'])
    stock_model.save()
    
    print stock['name']
Exemple #18
0
def fetchStocks():
    connect('stockenex')
    with open('s3://stockenex/colorMap.json', 'r') as c:
        colorMap = json.load(c)[1]
    with open('s3://stockenex/stockDataFileCount.txt') as fc:
        fileCount = int(fc.readline())

    Stock.objects.delete()
    for i in range(1, fileCount + 1):
        date = ""
        for line in open('s3://stockenex/stockData' + str(i) + '.csv'):
            if ('Symbol,"S, D","S, D"' in line
                    or "Trade in Profit Range" in line):
                continue
            if "Date" in line:
                date = line.split(",")[1]  #Date ,2020-05-06,
                continue
            lineInfo = line.split(',', 2)
            symbol = lineInfo[0]
            color = lineInfo[1].lower()
            if color == "cyan":
                color = "cyan3"
            if color in colorMap.keys():
                color = colorMap[color]
            color = string.upper(color)
            if color == "#005F00" or color == "#1CAC78":
                color = "#1CAC78"
            elif color == "#1F75FE" or color == "#000080" or color == "#00D7AF":
                color = "#00D7AF"

            value = lineInfo[2]

            st = Stock(symbol=symbol)
            if Stock.objects(Q(symbol=symbol)):
                st = Stock.objects(Q(symbol=symbol)).first()

            if color == "#FCE883":
                st.slw = []
                st.enwl = []
                st.enwh = []
                st.exwl = []
                st.exwh = []
                st.close = []
                st.high = []
                st.low = []
                st.date = []

            v = value

            LS = v.split(" ")[0]
            trend = v.split(" [ Enw=")[0].split('(')[1]
            enw = v.split("Enw= ")[1].split(" ")[0].split("(")[1].split(")")[0]
            exw = v.split("Exw= ")[1].split(" ")[0].split("(")[1].split(")")[0]
            if i > 3:
                slw = v.split("Slw= ")[1].split("]")[0]
            else:
                slw = v.split("Slw= ")[1].split(" ")[0].split("(")[1].split(
                    ")")[0]
            close = v.split("Close=")[1].split(" ")[0]
            high = v.split("High=")[1].split(" ")[0]
            low = v.split("Low=")[1].split(" ")[0]

            st.value = v
            st.color = color
            st.trend = trend
            st.LS = LS
            st.date.append(date)
            st.enwl.append(float(enw.split("-")[0]))
            st.enwh.append(float(enw.split("-")[1]))

            st.exwl.append(float(exw.split("-")[0]))
            st.exwh.append(float(exw.split("-")[1]))
            if i > 3:
                st.slw.append(float(slw))
            else:
                st.slw.append(float(slw.split("-")[0]))

            st.close.append(float(close))
            st.high.append(float(high))
            st.low.append(float(low))
            st.save()
    disconnect()
Exemple #19
0
def stock(request):
    groups = request.user.groups.all()
    groupList=[]
    for obj in groups:
        groupList.append(obj.name)
    usr=request.user
    if usr.is_superuser or 'stock' in groupList:
        companyObj=Company.objects.all()
        commodityObj=Commodity.objects.all()
        context={}
        context['companyObj']=companyObj
        # context['companyObjList']=json.dumps(list(companyObj))
        context['commodityObj']=commodityObj

        if request.method == 'POST':
            tp= request.POST.get('type1', None)
            stockObj=Stock()
            stockObj.type=request.POST.get('type1',None)
            stockObj.company_id=str(request.POST.get('company_Name',None))
            print str(request.POST.get('cmpAddress',None))
            stockObj.address_id=str(request.POST.get('cmpAddress',None))
            stockObj.bill_No=request.POST.get('bill_No',None)
            bill_Date = request.POST.get('bill_Date', None)
            if len(bill_Date)>4:
                stockObj.bill_Date=bill_Date
            bill_Rec_Date = request.POST.get('bill_Rec_Date', None)
            if len(bill_Rec_Date) > 4:
                stockObj.bill_Rec_Date=bill_Rec_Date
            try:
                bill_Amount = float(str(request.POST.get('bill_Amount', '')))
                stockObj.bill_Amount=bill_Amount
            except:
                pass

            stockObj.lr_No=request.POST.get('lr_No',None)
            lr_Date = request.POST.get('lr_Date', None)
            if len(lr_Date) > 4:
                stockObj.lr_Date=lr_Date
            stockObj.cases=request.POST.get('cases',None)
            stockObj.carriers_Name=request.POST.get('carriers_Name',None)
            stockObj.permit_No=request.POST.get('permit_No',None)
            try:
                permit_Amt = float(str(request.POST.get('permit_Amt', '')))
                stockObj.permit_Amt = permit_Amt
            except:
                pass
            stockObj.doc_Month=request.POST.get('doc_Month',None)
            stockObj.F_C_O=request.POST.get('F_C_O',None)
            date = request.POST.get('date', None)
            if len(date) > 4:
                stockObj.date=date
            stockObj.qrt=request.POST.get('qrt',None)
            stockObj.remarks=request.POST.get('remarks',None)
            stockObj.commodity_id=str(request.POST.get('commodity',None))
            stockObj.year=request.POST.get('year',None)
            stockObj.save()
            context['message']="Stock Added Successfully. Note down Record Id-"+str(stockObj.id)
            return render(request, 'stock.html',context)
        return render(request, 'stock.html',context)
    else:
        context={'errorCode':404,'errorMsg':'You dont have this permissions'}