Invoice lines sum - Odoo v8 - python

I'm trying to implement this scenario on invoice lines.
Let's say I have 50 products on my invoice line, 40 products are tax affected, and 10 aren't.
So, in the result of my invoice, I have two fields to compute this
exe = fields.Float(string='Monto Exento', digits=dp.get_precision('Account'),
store=True, readonly=True, compute='extras', track_visibility='always')
Should return the total of the 40 tax affected products, and this field
impo = fields.Float(string='Base Imponible', digits=dp.get_precision('Account'),
store=True, readonly=True, compute='extras', track_visibility='always')
Should return the total of the 10 other products, which aren't tax affected.
Now, I call this from a function, and compute the results:
#api.one
#api.depends('invoice_line.price_subtotal', 'tax_line.amount')
def extras(self):
self.exe = self.amount_untaxed + self.amount_tax
self.impo = self.amount_untaxed + self.amount_tax
rec=0
But it isn't working as expected, I don't know what could be wrong here, maybe it is because of how I'm handling this on extras function?
It just sums everything like the total amount of all the lines.
EDIT
Following #phillipstack answer, I've updated my code like this:
#api.one
#api.depends('invoice_line.price_subtotal', 'tax_line.amount')
def extras(self):
self.exe = self.amount_untaxed + self.amount_tax if self.amount_tax and self.amount_tax > 0 else 0
self.impo = self.amount_untaxed + self.amount_tax if not self.amount_tax or self.amount_tax == 0 else 0
But on impo field it just sums it all, taxed or not, I'm trying with one untaxed product, and one taxed.
On exe right it isn't showing any amount.
On exe it should show the total amount of untaxed products, and on impo it should show the total amount of taxed ones.
If You need more info please let me know.

You need to provide an if statement to tell your script to not sum if it meets certain criteria. I dont know enough about your requirements however this might work. Or something like this.
#api.one
#api.depends('invoice_line.price_subtotal', 'tax_line.amount')
def extras(self):
self.exe = self.amount_untaxed + self.amount_tax if self.amount_tax and self.amount_tax > 0 else 0
self.impo = self.amount_untaxed + self.amount_tax if not self.amount_tax or self.amount_tax == 0 else 0

Related

how to get price range with django?

i have price model
class Product(models.Model):
price = models.IntegerField
membership_discount = models.DecimalField
if i get price parameter, (ex. min_price = 100000, max_price = 500000)
I want to get the products multiplied by the price fields and membership_discount fields.
not this
Product.objects.filter(price__range = (min_price, max_price))
i want
Product.objects.filter(price * (1+membership_discount)__range = (min_price, max_price))
lte = less than or equal to
gte = greater than or equal to
this is documentation: https://docs.djangoproject.com/en/4.0/ref/models/querysets/#gt
max_price = #max price logic here
min_price = #min price logic her
#this will filter all products (price <= max_price and price >= min_price)
Product.objects.filter(price__lte = max_price, price__gte = min_price)
You could use annotations for the QuerySet and apply the filter on the annotation.
Product.objects.annotate(
member_price=F('price') * (1 + F('membership_discount'))
).filter(
member_price__range=(min_price, max_price)
)
If the pricefield and the membership_dicsount do not have the same type, you might need to make usage of the ExpressionWrapper with a specific output_field
Product.objects.annotate(
member_price=ExpressionWrapper(
F('price') * (1 + F('membership_discount')),
output_field=DecimalField()
)
).filter(
member_price__range=(min_price, max_price)
)
Docs:
https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.query.QuerySet.annotate
https://docs.djangoproject.com/en/4.0/topics/db/aggregation/
https://docs.djangoproject.com/en/4.0/ref/models/expressions/#using-f-with-annotations

how to do loop over the tickers and save result on the dictionary

I’m not so sure how to do the last part which is the dictionary part and ticker part, and also
On
“”file = open("/home/ubuntu/environment/hw5/" + tickers + “.txt”)””"
This line keep showing
TypeError: must be str, not list
Any suggestion on how to fix those or make the code works ?
Here’s my code
import json
def meanReversionStrategy(prices):
total_profit = 0
first_buy = None
buy = 0
for i in range(len(prices)):
if i >= 5:
current_price = prices[i]
moving_average = (prices[i-1] + prices[i-2] + prices[i-3] + prices[i-4] +prices[i-5]) / 5
if current_price < moving_average * 0.95 and buy == 0:
buy = current_price
print("buy at: ",round (current_price,2))
if first_buy is None:
first_buy = buy
elif current_price > moving_average * 1.05 and buy != 0:
print("sell at: ", round(current_price,2))
print("trade profit: ", round(current_price - buy,2))
total_profit = current_price - buy
buy = 0
final_profit_percentage = ( total_profit / first_buy ) * 100
print("First buy: " , round(first_buy,2))
print("Total profit: " , round(total_profit, 2))
print("Percentage return: ", round(final_profit_percentage, 2),"%")
def simpleMovingAverageStrategy(prices):
i = 0
buy = 0
total_profit = 0
first_buy = 0
for p in prices:
if i >= 5:
moving_average = (prices[i-1] + prices[i-2] + prices[i-3] + prices[i-4] +
prices[i-5]) / 5
#simple moving average logic, not mean
if p > moving_average and buy == 0: #buy
print("buying at: ", p)
buy = p
if first_buy == 0:
first_buy = p
elif p < moving_average and buy != 0: #sell
print("selling at: ", p)
print("trade profit: ", p - buy)
total_profit += p - buy
buy = 0
i += 1
final_percentage = (total_profit / first_buy) * 100
print("first buy: ", first_buy)
print("total profit: ", total_profit)
print("final percentage: ", final_percentage, "%")
return total_profit, final_percentage
tickers = ["AAPL1" , "ADBE" , "BA", "CMCSA", "CSCO", "CVS", "GOOG", "TLSYY","TM"]
file = open("/home/ubuntu/environment/hw5/" + tickers + ".txt")
lines = file.readlines()
# print(lines)
prices = []
for line in lines:
prices.append(float(line))
profit, returns = simpleMovingAverageStrategy(prices)
results = {}
results["AAPL1_profit"] =profit
results["AAPL1_returns"] = returns
json.dump(results, open("/home/ubuntu/environment/hw5/results.json", "w") )
Coding Requirements
-Create a function called meanReversionStrategy which takes a list called “prices” as an argument. The function runs a mean reversion strategy, and outputs to the console the buys and sells of the strategy (like you did in HW4). The function returns the profit and final returns percentage.
-Create a function called simpleMovingAverageStrategy which takes a list called “prices” as an argument. The function runs a Simple Moving Average strategy, and outputs to the console the buys and sells of the strategy. The function returns the profit and final returns percentage.
-Create a function called saveResults which takes a dictionary as an argument. Save the dictionary to a json file called “results.json”.
loop through the list of tickers
for ticker in tickers:
-load prices from a file <ticker>.txt, and store them in the results dictionary with the
key “<ticker>_prices”
-call meanReversionStrategy(prices) and store the profit and returns in the results
dictionary with the keys “<ticker>_mr_profit” and “<ticker>_mr_returns”
-call simpleMovingAverageStrategy(prices) and store the profit and returns in the
results dictionary with the keys “<ticker>_sma_profit” and “<ticker>_sma_profit”
with the keys “ticker_mr_profit” and “ticker_mr_returns”
call saveResults(results) and save the results dictionary to a file called results.json
Welcome!
As this is a homework question, I will not solve it for You, but here is my advice for You:
tickers is an array and as your homework description states, You must 'loop through the list of tickers' and open each of them. So how do You loop over tickers?
And reflect about the error. What do You think should be the result of "/home/ubuntu/environment/hw5/" + tickers + ".txt"?

How to loop the following code in Python?

I am new to Python but I tried to create the following trading strategy but cannot find a way to loop it for different products (trading hours in this case).
def strategy(area_code, product, orders, environment):
order = None
new_orders = []
Quantity = 5
price_delta = 0.1
def process_flex(Plant):
order = None
Tur1 = Plant + "1"
if Tur1Volume > 0:
if Tur1Price:
order = None
if check_if_we_have_order_on_the_market(Plant,Tur1)==0:
order = package.create_sell_order(area_code, Tur1Volume, Quantity, calculate_selling_price(Tur1Price), price_delta, product, environment.current_datetime).with_label((Plant,Tur1))
if order:
new_orders.append(order)
else:
order = None
return
process_flex("bla")
process_flex("blabla")
process_flex("blablabla")
return new_orders
This code is only working for one product (1 hour) and does not loop for all 24 products.
I thought that it could work like this:
for product in products:
Plant = ['bla', 'blabla', 'blablabla']
for i in Plant:
order = process_flex(Plant)
return_orders.append(order)
return return_orders
Unfortunately, it did not work. Do you have any idea on the solution?
Thank a lot in advance!
You want to swap Plant to :
order = process_flex(i)
because i is an element of Plant
for product in products:
Plant = ['bla', 'blabla', 'blablabla']
for i in Plant:
order = process_flex(i)
return_orders.append(order)
return return_orders

Odoo 8 Allow Negative Invoice Line Item

I have a product called "Coupon" with negative amount which is used to offset the product price. However, it seems like Odoo 8 does not allow computation of negative amount to price_subtotal (it becomes 0.00):
Coupon ... ... 1 Each -40.0000 0.0000
When I remove the negative sign, it computes
Coupon ... ... 1 Each 40.0000 40.0000
From an accounting perspective, the total invoice should not be negative. That stays true. However, I do need to allow negative computation of invoice line item(s). Where and what do I need to change? I tried looking into account/account.py but to no avail so far - it's all just "tax" related.
Thanks in advance!
Details of the amount column for the line total
class account_invoice(models.Model)
....
#api.one
#api.depends('invoice_line.price_subtotal', 'tax_line.amount')
def _compute_amount(self):
self.amount_untaxed = sum(line.price_subtotal for line in self.invoice_line)
self.amount_tax = sum(line.amount for line in self.tax_line)
self.amount_total = self.amount_untaxed + self.amount_tax
....
class account_invoice_line(models.Model):
_name = "account.invoice.line"
_description = "Invoice Line"
_order = "invoice_id,sequence,id"
#api.one
#api.depends('price_unit', 'discount', 'invoice_line_tax_id', 'quantity',
'product_id', 'invoice_id.partner_id', 'invoice_id.currency_id')
def _compute_price(self):
price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
taxes = self.invoice_line_tax_id.compute_all(price, self.quantity, product=self.product_id, partner=self.invoice_id.partner_id)
self.price_subtotal = taxes['total']
if self.invoice_id:
self.price_subtotal = self.invoice_id.currency_id.round(self.price_subtotal)
#api.model
def _default_price_unit(self):
if not self._context.get('check_total'):
return 0
total = self._context['check_total']
for l in self._context.get('invoice_line', []):
if isinstance(l, (list, tuple)) and len(l) >= 3 and l[2]:
vals = l[2]
price = vals.get('price_unit', 0) * (1 - vals.get('discount', 0) / 100.0)
total = total - (price * vals.get('quantity'))
taxes = vals.get('invoice_line_tax_id')
if taxes and len(taxes[0]) >= 3 and taxes[0][2]:
taxes = self.env['account.tax'].browse(taxes[0][2])
tax_res = taxes.compute_all(price, vals.get('quantity'),
product=vals.get('product_id'), partner=self._context.get('partner_id'))
for tax in tax_res['taxes']:
total = total - tax['amount']
return total
Odoo's default behaviour is handling it as expected. The problem is custom code. (For more information read the questions comments)

Calculate the future value for only one category using the IRR (Python)

import xlrd
import numpy
fileWorkspace = 'C://Users/jod/Desktop/'
wb1 = xlrd.open_workbook(fileWorkspace + 'assign2.xls')
sh1 = wb1.sheet_by_index(0)
time,amount,category = [],[],[]
for a in range(2,sh1.nrows):
time.append(int(sh1.cell(a,0).value)) # Pulling time from excel (column A)
amount.append(float(sh1.cell(a,1).value)) # Pulling amount from excel (column B)
category.append(str(sh1.cell(a,2).value)) # Pulling category from excel (column C)
#print(time)
#print(amount)
#print(category)
print('\n')
p_p2 = str(sh1.cell(0,1))
p_p1 = p_p2.replace("text:'","")
pp = p_p1.replace("'","")
print(pp) # Printing the type of pay period (Row 1, col B)
c_p2 = str(sh1.cell(1,1))
c_p1 = c_p2.replace("text:'","")
cp = c_p1.replace("'","")
print(cp) # Printing the type of compound period (Row 2, col B)
netflow = 0
outflow = 0
inflow = 0
flow = 0
cat = ["Sales", "Salvage", "Subsidy", "Redeemable", "Utility", "Labor",
"Testing", "Marketing", "Materials", "Logistics"]
if pp == "Years" and cp == "Years": # if pay period and compound period are both in years
IRR = numpy.irr(amount) * 100 # Calculates the internal rate of return (IRR)
print ("IRR:", round(IRR, 2), '%', '\n') # prints (IRR)
for i in time: # for every value in time array
if cat[5] in category: # if "Labor" for cat array is in category array or not
# calculates the present values using all the amount values (col B) instead of
# just using the ones that has "Labor" category label beside them
# Need to make every other value 0, such as beside "Redeemable" and "Salvage"
flow = amount[i] / numpy.power((1 + (IRR/100)), time[i])
if flow>0:
inflow = inflow + flow
if flow<0:
outflow = outflow + flow
print ('Present Value (P) is:', round(flow,0), '\n')
netflow = outflow + inflow
print("In year 0 or current year")
print("-------")
print ('Outflow is: ', round(outflow,0))
print ('Inflow is: ', round(inflow,0))
print ('Netflow is: ', round(netflow,0), '\n')
outflow2 = (round(outflow,0))*(1+(IRR/100))**(9)
inflow2 = (round(inflow,0))*(1+(IRR/100))**(9)
netflow2 = outflow2 + inflow2
print("In year 9")
print("-------")
print ('Outflow is: ', round(outflow2,0))
print ('Inflow is: ', round(inflow2,0))
print ('Netflow is: ', round(netflow2,0), '\n')
I have commented important lines of code for clarification.
Here is the original question:
illustrate the breakdown of major project revenues and expenses by category as a percentage of that project’s future value in year 9. The illustration must also clearly indicate the total future value of the project in year 9 as well as the IRR.
There will be a total of 10 revenue and cost categories that a project may be composed of. The categories are: Sales, salvage, subsidy, redeemable, utility, labor, testing, marketing, materials and logistics. All revenues and expenses will fall in one of these ten categories. The project pay period and compound period will be identified at the top of the Excel sheet. Pay period and compound period may be designated as any of the following: years, quarters, months.
I am getting confused because I am not able to pull the only values from beside the "Labor", "Redeemable", or "Salvage". I just don't know where I am making a mistake, or there is something that is incomplete. Below is the excel file image:
Excel File Image 2
Excel File Image 3
After revising, all cashflows are discounted at the irr. What is done is the following:
i) determineAdjustments takes the pay period (column A) and adjusts if for the year ended (if it is a monthly amount it puts it in the proper year ended) and if its monthly puts in in the month ended (no adjustment necessary). This will divide the pay period by 12 if yearly cash flows are needed (yearly compounding)
ii) IRR is calculated, and the compounding period is used to adjust the monthly IRR for monthly pay periods
iii) all expenses are discounted at the IRR and input into a list for cat_contributions['category_name'] = [discounted period 1, discounted period 2 ... ]
iv) Then the net inflows and outflows are sums of these.
I can't type up data in the spreadsheets from the images as that would take a while, but maybe tinker with this and see if you can get it to work.
from __future__ import division
import xlrd
import numpy
import os
import math
def main(xls = 'xls_name.xlsx', sh = 0):
#save script in same folder as the xls file
os.chdir( os.getcwd() )
wb = xlrd.open_workbook(xls)
sh = wb.sheet_by_index(0)
pay_period = sh.cell_value(0,1)
compounding_period = sh.cell_value(1,1)
compounding_factor, pay_factor = determineAdjustments(
pay_period, compounding_period)
number_of_periods = max( sh.col_values(0, start_rowx = 2) )
flow_per_period = [ 0*i for i in range( int( math.ceil( number_of_periods/pay_factor ) ) + 1 ) ]#list of length number of pay_periods
for r in range(2,sh.nrows):
pay_period = int( math.ceil( sh.cell_value(r,0) / pay_factor ) )
flow_per_period[pay_period] += sh.cell_value(r,1) #unadjusted cash flows
irr = calculateIRR(flow_per_period, compounding_factor)
cat_contributions = sortExpenditures(sh, irr, pay_factor)
total_cat_contributions, netflow, total_outflow, total_inflow = calculateFlows(cat_contributions)
printStats(cat_contributions, irr, compounding_factor, pay_factor,
total_cat_contributions, netflow, total_outflow, total_inflow)
return
def determineAdjustments(pay_period, compounding_period):
if compounding_period == 'years':
compounding_factor = 1
if pay_period == 'months':
pay_factor = 12
if pay_period == 'years':
pay_factor = 1
#assume no days pay periods
if compounding_period == 'months':
compounding_factor = 12
#assume no yearly payouts and that the
#all payments are in months
pay_factor = 1
return compounding_factor, pay_factor
def calculateIRR(cashflow, compounding_factor):
irr = numpy.irr(cashflow)
irr_comp = (1 + irr)**compounding_factor - 1
#seems like in first example it uses rounded irr, can do something like:
#irr_comp = round(irr_comp,4)
return irr_comp
def sortExpenditures(sh, irr, pay_factor):
#percentages and discounting occurs at the IRR caculated in the main
#function
cat = ["Sales", "Salvage", "Subsidy", "Redeemable", "Utility", "Labor",
"Testing", "Marketing", "Materials", "Logistics"]
#python dictionary to sort contributions into categories
cat_contributions = {}
for c in cat:
cat_contributions[c] = []
# create list of contributions of each list item to FV in a dictionary
for r in range(2,sh.nrows):
try:
#discounted cash flow of each expenditure
#using formula FV = expenditure/(1+i)^n
cat_contributions[sh.cell_value(r,2)].append(
sh.cell_value(r,1) / ( (1 + irr) ** (sh.cell_value(r,0)/pay_factor) )
)
except KeyError:
print "No category for type: " + sh.cell_value(r,2) +'\n'
return cat_contributions
def calculateFlows(cat_contributions):
total_outflow = 0
total_inflow = 0
total_cat_contributions = {}
for cat in cat_contributions:
total_cat_contributions[cat] = sum( cat_contributions[cat] )
if total_cat_contributions[cat] < 0:
total_outflow += total_cat_contributions[cat]
else:
total_inflow += total_cat_contributions[cat]
netflow = total_inflow + total_outflow
return total_cat_contributions, netflow, total_outflow, total_inflow
def printStats(cat_contributions, irr, compounding_factor, pay_period,
total_cat_contributions, netflow, total_outflow, total_inflow):
print "IRR: "+str(irr*100) +' %'
if compounding_factor == 1: print "Compounding: Yearly"
if compounding_factor == 12: print "Compounding: Monthly"
if pay_period == 1: "Cashflows: Year Ended"
if pay_period == 12: "Cashflows: Month Ended"
print "Future Value (Net Adjusted Cashflow): " +str(netflow)
print "Adjusted Inflows: " + str(total_inflow)
print "Adjusted Outflows: " + str(total_outflow) +'\n'
for cat in total_cat_contributions:
if total_cat_contributions[cat] != 0:
print '-----------------------------------------------------'
print cat + '\n'
print "Total Contribution to FV " + str( total_cat_contributions[cat] )
if total_cat_contributions[cat] < 0:
print "Contribution to Expenses: " + str ( abs(100 * total_cat_contributions[cat]/total_outflow) )
else:
print "Contribution to Revenues: " + str ( abs(100 * total_cat_contributions[cat]/total_inflow) ) +'\n'
main(xls='Book1.xlsx')

Categories