当前位置: 首页>>代码示例>>Python>>正文


Python Stock.save方法代码示例

本文整理汇总了Python中models.Stock.save方法的典型用法代码示例。如果您正苦于以下问题:Python Stock.save方法的具体用法?Python Stock.save怎么用?Python Stock.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在models.Stock的用法示例。


在下文中一共展示了Stock.save方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: portfolio_add_stock

# 需要导入模块: from models import Stock [as 别名]
# 或者: from models.Stock import save [as 别名]
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('')
开发者ID:Mandibull,项目名称:django_stock_portfolio,代码行数:9,代码来源:views.py

示例2: update_symbols

# 需要导入模块: from models import Stock [as 别名]
# 或者: from models.Stock import save [as 别名]
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()
开发者ID:antonigno,项目名称:finance-game,代码行数:32,代码来源:utils.py

示例3: agregar_stock

# 需要导入模块: from models import Stock [as 别名]
# 或者: from models.Stock import save [as 别名]
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()
开发者ID:soncco,项目名称:distri,代码行数:10,代码来源:utils.py

示例4: BeginToTrade

# 需要导入模块: from models import Stock [as 别名]
# 或者: from models.Stock import save [as 别名]
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)
开发者ID:Alchemyst2802,项目名称:SES-Group,代码行数:58,代码来源:views.py

示例5: stock_summary

# 需要导入模块: from models import Stock [as 别名]
# 或者: from models.Stock import save [as 别名]
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})
开发者ID:dannyshafer,项目名称:Chrysalis-Mutual-Funds-Python-Django-,代码行数:57,代码来源:views.py

示例6: show_stock

# 需要导入模块: from models import Stock [as 别名]
# 或者: from models.Stock import save [as 别名]
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})
开发者ID:sapenagamero0,项目名称:teststock2,代码行数:17,代码来源:views.py

示例7: stock_add

# 需要导入模块: from models import Stock [as 别名]
# 或者: from models.Stock import save [as 别名]
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)
    )
开发者ID:mrcrgl,项目名称:stockstore,代码行数:48,代码来源:views.py

示例8: import_data

# 需要导入模块: from models import Stock [as 别名]
# 或者: from models.Stock import save [as 别名]
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)
开发者ID:DataSciCode,项目名称:finance,代码行数:45,代码来源:snapshot.py

示例9: stock

# 需要导入模块: from models import Stock [as 别名]
# 或者: from models.Stock import save [as 别名]
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'}
开发者ID:abhishekbkhemka,项目名称:kalapatru,代码行数:63,代码来源:views.py

示例10: store_stock

# 需要导入模块: from models import Stock [as 别名]
# 或者: from models.Stock import save [as 别名]
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']
开发者ID:macvaz,项目名称:stocks,代码行数:7,代码来源:services.py

示例11: transaction

# 需要导入模块: from models import Stock [as 别名]
# 或者: from models.Stock import save [as 别名]
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')
开发者ID:guillaume-miara,项目名称:mista,代码行数:74,代码来源:views.py


注:本文中的models.Stock.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。