'Get weighted average of valuation rate from all warehouses'

def get_valuation_rate(self, args):

    (total_qty, total_value, valuation_rate) = (0.0, 0.0, 0.0)
    for d in frappe.db.sql(u'select    actual_qty,    stock_value    from    `tabBin`\n DCTB  DCTB  DCTB where    item_code=%s', args[u'item_code'], as_dict=1):
        total_qty += flt(d.actual_qty)
        total_value += flt(d.stock_value)
    if total_qty:
        valuation_rate = (total_value / total_qty)
    if (valuation_rate <= 0):
        last_valuation_rate = frappe.db.sql(u'select    valuation_rate\n DCTB  DCTB  DCTB  DCTB from    `tabStock    Ledger    Entry`\n DCTB  DCTB  DCTB  DCTB where    item_code    =    %s    and    valuation_rate    >    0\n DCTB  DCTB  DCTB  DCTB order    by    posting_date    desc,    posting_time    desc,    name    desc    limit    1', args[u'item_code'])
        valuation_rate = (flt(last_valuation_rate[0][0]) if last_valuation_rate else 0)
    return valuation_rate
