Generic function to unwind portfolio - iteration

I have following sample portfolio p of positions (signed_qty) acquired daily:
p:([]date:(2013.07.01+1000#til 200);bb_code:((200#`TSLA),(200#`MSFT),(200#`GOOG),(200#`GS),(200#`AAPL));fill_px:1000?10e; signed_qty:(1000?(-1, 1)) * 1000?10000);
I want to estimate daily trades and position for different unwind strategies. Some of the different strategies that I want to back-test are as follows:
Hold for 2 days and then trade out in next 3 days. (n=2, m=3)
Hold for 1 day and then trade out in next 4 days. (n=1, m=4)
Trade evenly in next 4 days. (n=0, m=4)
... so on.
Below is the verbose code to do so for n=3, m=4. Can someone suggest a more elegant and generic way to get output for various n and m.?
/Adding prev_bb_code column to facilitate computation
p:update prev_bb_code: prev bb_code from p;
/No trading t+1.
p:update qty:prev signed_qty from p;
p:update signed_qty_p1:qty from p where bb_code = prev_bb_code;
p:update traded_qty_p1:(signed_qty_p1 - qty) from p;
/No trading t+2.
p:update qty:prev signed_qty_p1 from p;
p:update signed_qty_p2:qty from p where bb_code = prev_bb_code;
p:update traded_qty_p2:(signed_qty_p2 - qty) from p;
/1st trade (=1/4th position acquired on t) generated on t+3 with carry forward position = 3/4.
p:update qty:prev signed_qty_p2 from p;
p:update signed_qty_p3:"f"${$[x<0; ceiling((3%4.0)*x); floor((3%4.0)*x)]} each qty from p where bb_code = prev_bb_code;
p:update traded_qty_p3:(signed_qty_p3 - qty) from p;
/2nd trade (=1/4th position acquired on t) generated on t+4 with carry forward position = 2/4.
p:update qty:prev qty, prev_qty:prev signed_qty_p3 from p;
p:update signed_qty_p4:"f"${$[y=0n;0n;$[x<0; max((ceiling((2%4.0)*x)),y); min((floor((2%4.0)*x)),y)]]}'[qty; prev_qty] from p where bb_code=prev_bb_code;
p:update traded_qty_p4:(signed_qty_p4 - prev_qty) from p;
/3rd trade (=1/4th position acquired on t) generated on t+5 with carry forward position = 1/4.
p:update qty:prev qty, prev_qty:prev signed_qty_p4 from p;
p:update signed_qty_p5:"f"${$[y=0n;0n;$[x<0; max((ceiling((1%4.0)*x)),y); min((floor((1%4.0)*x)),y)]]}'[qty; prev_qty] from p where bb_code=prev_bb_code;
p:update traded_qty_p5:(signed_qty_p5 - prev_qty) from p;
/4th trade (=1/4th position acquired on t) generated on t+6 with carry forward position = 0. This abso
p:update qty:prev qty, prev_qty:prev signed_qty_p5 from p;
p:update signed_qty_p6:"f"${$[y=0n;0n;$[x<0; max((ceiling((0%4.0)*x)),y); min((floor((0%4.0)*x)),y)]]}'[qty; prev_qty] from p where bb_code=prev_bb_code;
p:update traded_qty_p6:(signed_qty_p6 - prev_qty) from p;
/Aggregate trades and positions.
p:update unwind_qty:((0^traded_qty_p1) + (0^traded_qty_p2) + (0^traded_qty_p3) + (0^traded_qty_p4) + (0^traded_qty_p5) + (0^traded_qty_p6)) from p;
p:update net_position:((0^signed_qty) + (0^signed_qty_p1) + (0^signed_qty_p2) + (0^signed_qty_p3) + (0^signed_qty_p4) + (0^signed_qty_p5) + (0^signed_qty_p6)) from p;
/ Finally only retain the columns of interest.
p: select date, bb_code, fill_px, signed_qty, unwind_qty, net_position from p;

This can be achieved with xprev and functional form.
https://code.kx.com/q/ref/next/#xprev
https://code.kx.com/q/basics/funsql/
Edit: This can actually be achieved without functional form:
g:{[n;m;x] sums[x]+sums sum each neg (flip xprev[;x] each n + til m)%m}
update net_position:g[3;4;signed_qty] by bb_code from t
Original Answer:
f:{[t;n;m]
//[table;where;by;cols]
![t;();(enlist `bb_code)!(enlist `bb_code);
(enlist `net_position)!enlist
// cumulative position change
(+;(sums;`signed_qty);
// cumulative unwind position change
// neg to invert the sign to unwind in opposite direction to original position
(sums;(each;sum;(neg;
// this part dynamically builds the number of xprev's required
// n being the start / hold period
// m for the number of unwind periods
(%;(flip;(enlist),(xprev),/:(n + til m),'`signed_qty);m)))))]
}
// No Comments
f:{[t;n;m]
![t;();(enlist `bb_code)!(enlist `bb_code);(enlist `net_position)!enlist (+;(sums;`signed_qty);(sums;(each;sum;(neg;(%;(flip;(enlist),(xprev),/:(n + til m),'`signed_qty);m)))))]
};
q)f[p;3;4]
date bb_code fill_px signed_qty net_position
-----------------------------------------------------
2013.07.01 TSLA 4.695818 8159 8159
2013.07.02 TSLA 0.747672 2203 10362
2013.07.03 TSLA 8.014479 -566 9796
2013.07.04 TSLA 3.805866 -831 8965
2013.07.05 TSLA 2.884907 -7792 -866.75
2013.07.06 TSLA 1.303814 9188 5730.75
2013.07.07 TSLA 8.517136 2267 5548.75
2013.07.08 TSLA 5.645172 5352 8659.5
2013.07.09 TSLA 0.04426234 7867 18273

Related

Confirm Sale and skip Payment - net_amount is getting added to prev_outstanding_balance

I'm using (Bahmni with) Odoo-10 and when I press Confirm button in the Sale Order and skip/cancel the Register Payment step, the Total Outstanding amount is displayed as double the actual amount.
Here, the Previous Balance field is taking the amount in the current sale order, and then this value is also getting added with the Net Amount.
When I check the bahmni-erp/bahmni-addons/bahmni_sale/models/sale_order.py, I observe this code under SaleOrder class
prev_outstanding_balance = fields.Monetary(string="Previous Outstanding Balance",
compute=_calculate_balance)
total_outstanding_balance = fields.Monetary(string="Total Outstanding Balance",
compute=_amount_all)
def _calculate_balance(self):
for order in self:
order.prev_outstanding_balance = 0.0
order.total_outstanding_balance = 0.0
total_receivable = order._total_receivable()
order.prev_outstanding_balance = total_receivable
def _amount_all(self):
"""
Compute the total amounts of the SO.
"""
for order in self:
...
order.update({
'amount_untaxed': order.pricelist_id.currency_id.round(amount_untaxed),
'amount_tax': order.pricelist_id.currency_id.round(amount_tax),
'amount_total': amount_total + round_off_amount,
'round_off_amount': round_off_amount,
'total_outstanding_balance': order.prev_outstanding_balance + amount_total + round_off_amount
})
def _total_receivable(self):
receivable = 0.0
if self.partner_id:
self._cr.execute("""SELECT l.partner_id, at.type, SUM(l.debit-l.credit)
FROM account_move_line l
LEFT JOIN account_account a ON (l.account_id=a.id)
LEFT JOIN account_account_type at ON (a.user_type_id=at.id)
WHERE at.type IN ('receivable','payable')
AND l.partner_id = %s
AND l.full_reconcile_id IS NULL
GROUP BY l.partner_id, at.type
""", (self.partner_id.id,))
for pid, type, val in self._cr.fetchall():
if val is None:
val=0
receivable = (type == 'receivable') and val or -val
return receivable
Why it's adding the Net Amount in the current Sale Order to the prev_outstanding_balance?
Please help.
Thanks.

Amibroker AFL: How to plot Custom Anchored VWAP (AVWAP) passing any specific date to it

Below is the code for Anchored VWAP which will select Date based on my mouse click, my query is how to plot Anchored VWAP passing date as a parameter, so it will be constant across all symbols.
Eg: I want to pass "2021-03-26" as Date parameter so it will plot AVWAP starting from "2021-03-26" date.
_SECTION_BEGIN("CustomAVWAP");
dn = DateTime();
sd = SelectedValue( dn );
start = dn == sd;
mp = C;
PV = mp * V;
CV = Cum( V );
VSS = CV - ValueWhen( start, CV );
denom = IIf( VSS == 0, 1, VSS );
num = Cum( PV ) - ValueWhen( start, Cum( PV ) );
M = IIf( BarsSince( start ), num/denom, mp );
Plot( C, Date() + " Close", colorBrightGreen, styleBar );
Plot( M, "PSVWAP", colorBrightGreen, styleThick );
_SECTION_END();

How TradingView Pine Script RMA function works internally?

I'm trying to re-implement the rma function from TradingView pinescript but I cannot make it output the same result as the original function.
Here is the code I developed, the code is basically the ema function, but it differs greatly from the rma function plot result when charting:
//#version=3
study(title = "test", overlay=true)
rolling_moving_average(data, length) =>
alpha = 2 / (length + 1)
sum = 0.0
for index = length to 0
if sum == 0.0
sum := data[index]
else
sum := alpha * data[index] + (1 - alpha) * sum
atr2 = rolling_moving_average(close, 5)
plot(atr2, title="EMAUP2", color=blue)
atr = rma(close, 5)
plot(atr, title="EMAUP", color=red)
So my question is how is the rma function works internally so I can implement a clone of it?
PS. Here is the link to the documentation https://www.tradingview.com/study-script-reference/#fun_rma It does show a possible implementation, but it does not work when running it.
Below is the correct implementation:
plot(rma(close, 15))
// same on pine, but much less efficient
pine_rma(x, y) =>
alpha = 1/y
sum = 0.0
sum := alpha * x + (1 - alpha) * nz(sum[1])
plot(pine_rma(close, 15))
There is a mistake in the code on TradingView, the alpha should be 1/y not y. This Wikipedia page has the correct formula for RMA
Wikipedia - moving averages

Check if Bezier Curve is sub-curve of another Bezier

I want to check if a cubic Bezier curve is a sub-curve of another Bezier.
I think I understand basically how to do this, express the Beziers as two cubics, in x and y, then test if the cubics are scalings or translations of each other. If the scaling and translations match that tells us the curves are sub-segments of the same curve and gives us t0 prime and t1 prime of curve B in curve As space.
But I can't quite work out how to check the cubics for equivalence.
Answer based on the following comment:
Say we take a Bezier Curve, and split it up using de Casteljau's algorithm. Obviously the result is a lot of sub-curves of the original curve.The question is how to go back, and recover the t values, and the fact that the curves are part of the same curve, given only their 4 control points
Short answer: unless you have an infinite precision machine, you can't.
So we're stuck with "error threshold" testing. Given a master curve A and a "hopefully subcurve" curve B, run through the things that need to be true if B was a subcurve of A:
If B is a true subcurve then its start and end point lie on curve A. So check if that's true, within some error threshold. If they don't, then B is not a subcurve of A.
If B is a true subcurve then the derivatives at B's start and end points are the same as the derivatives for the corresponding coordinates on A. So check if that's true, within some error threshold. If they're not, B is not a subcurve of A.
If B is a true subcurve then the second derivatives at B's start an end points are the same as the second derivatives for the corresponding coordinates on A. So check if that's true, within some error threshold. If they're not, B is not a subcurve of A.
If all of these hold, we can be reasonably sure that B is a subcurve of A.
Also, since we need to come up with t values in order to check whether a point lies on A, and what derivative of A is at that point, we already know the t values that define the interval on A that maps to the full curve B.
Here's the working code.
(You can find cubic root finders quite easily)
/*
A = p3 + 3.0 * p1 - 3.0 * p2 - p0;
B = 3.0 * p0 - 6.0 * p1 + 3.0 * p2;
C = 3.0 * p1 - 3.0 * p0;
D = p0;
*/
bool CurveIsSubCurve(BezierCurve bez, BezierCurve sub, double epsilon, double *t)
{
int Nr;
double tcand[6];
int i, ii;
double ts[6], te[6];
int Ns = 0;
int Ne = 0;
Vector2 p;
/*
Take two bites at the cherry. The points may have slight errors, and a small error in x or y could represent a big error in
t. However with any luck either x or y will be close
*/
Nr = cubic_roots(bez.Ax(), bez.Bx(), bez.Cx(), bez.Dx() - sub.P0().x, tcand);
Nr += cubic_roots(bez.Ay(), bez.By(), bez.Cy(), bez.Dy() - sub.P0().y, tcand + Nr);
for(i=0;i<Nr;i++)
{
p = bez.Eval(tcand[i]);
if(fabs(p.x - sub.P0().x) < epsilon && fabs(p.y - sub.P0().y) < epsilon)
{
ts[Ns++] = tcand[i];
}
}
/* same thing of sub curve end point */
Nr = cubic_roots(bez.Ax(), bez.Bx(), bez.Cx(), bez.Dx() - sub.P3().x, tcand);
Nr += cubic_roots(bez.Ay(), bez.By(), bez.Cy(), bez.Dy() - sub.P3().y, tcand + Nr);
for(i=0;i<Nr;i++)
{
p = bez.Eval(tcand[i]);
if(fabs(p.x - sub.P3().x) < epsilon && fabs(p.y - sub.P3().y) < epsilon)
{
te[Ne++] = tcand[i];
}
}
/* do an all by all to get matches (Ns, Ne will be small, but if
we have a degenerate, i.e. a loop, the loop intersection point is
where the mother curve is quite likely to be cut, so test everything*/
for(i = 0; i < Ns; i++)
{
double s,d;
double Ax, Bx, Cx, Dx;
double Ay, By, Cy, Dy;
for(ii=0;ii<Ne;ii++)
{
s = (te[ii] - ts[i]);
d = ts[i];
/* now substitute back */
Ax = bez.Ax() *s*s*s;
Bx = bez.Ax() *2*s*s*d + bez.Ax()*s*s*d + bez.Bx()*s*s;
Cx = bez.Ax()*s*d*d + bez.Ax()*2*s*d*d + bez.Bx()*2*s*d + bez.Cx() * s;
Dx = bez.Ax() *d*d*d + bez.Bx()*d*d + bez.Cx()*d + bez.Dx();
Ay = bez.Ay() *s*s*s;
By = bez.Ay() *2*s*s*d + bez.Ay()*s*s*d + bez.By()*s*s;
Cy = bez.Ay()*s*d*d + bez.Ay()*2*s*d*d + bez.By()*2*s*d + bez.Cy() * s;
Dy = bez.Ay() *d*d*d + bez.By()*d*d + bez.Cy()*d + bez.Dy();
if(fabs(Ax - sub.Ax()) < epsilon && fabs(Bx - sub.Bx()) < epsilon &&
fabs(Cx - sub.Cx()) < epsilon && fabs(Dx - sub.Dx()) < epsilon &&
fabs(Ay - sub.Ay()) < epsilon && fabs(By - sub.By()) < epsilon &&
fabs(Cy - sub.Cy()) < epsilon && fabs(Dy - sub.Dy()) < epsilon)
{
if(t)
{
t[0] = ts[i];
t[1] = te[ii];
}
return true;
}
}
}
return false;
}

I am stuck on my programming project

A large company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% of their gross sales for that week. For example, a salesperson who sells $5000 worth of merchandise in a week receives $200 plus 9% of $5000, or a total of $650. Your program will allow the user to enter item numbers for each item sold by the salesperson for that week, print out the total of each item sold by the salesperson, and the total weekly earnings for that salesperson. The items and values are: Item 1 equals to 5.00, Item 2 equals to 10.00, Item 3 equals to 1.00, Item 4 equals to 25.00. Program should use JOptionPane for all input.
I have some programmed but I only get one input.
--- Update ---
//This is what I have so far
import javax.swing.JOptionPane;
public class KingRocker {
public static void main( String[]args )
{
double gross = 0.0, earnings;
int product = 0, number;
String input;
while( product < 4 ){
product++;
input = JOptionPane.showInputDialog("Enter the number of products sold #" + product + " ");
number = Integer.parseInt( input );
if (product == 1)
gross = gross + number * 5.00;
else if (product == 2)
gross = gross + number * 10.00;
else if (product == 3)
gross = gross + number * 1.00;
else if (product == 4)
gross = gross + number * 25.00;
earnings = 0.09 * gross + 200;
String result = "Week earnings: " + earnings;
JOptionPane.showMessageDialog(null, result, "Sales", JOptionPane.INFORMATION_MESSAGE );
System.exit( -1);
}
}
}
From what I can tell, you are calling System.exit( -1); before you run though the rest of your while loop. Try moving System.exit( -1); outside of the loop.
Try closing the loops here
if (product == 1)
gross = gross + number * 5.00;
else if (product == 2)
gross = gross + number * 10.00;
else if (product == 3)
gross = gross + number * 1.00;
else if (product == 4)
gross = gross + number * 25.00;
}
Doing so will allow the loop to run four times. Giving you what you ask for in the comments.