iPhone SDK Present Value function - iphone

Present value is the value on a given date of a future payment or series of future payments, discounted to reflect the time value of money and other factors such as investment risk. Present value calculations are widely used in business and economics to provide a means to compare cash flows at different times on a meaningful "like to like" basis.
http://en.wikipedia.org/wiki/Present_value
What would be the best way to tackle this in an Objective-C function?
double retire62 = [benefit62.text doubleValue] * [yearlyReturn.text doubleValue] *12* [lblAgeExpectancy.text doubleValue];
double retire66 = [benefit66.text doubleValue] * [yearlyReturn.text doubleValue] *12* [lblAgeExpectancy.text doubleValue];
double retire70 = [benefit70.text doubleValue] * [yearlyReturn.text doubleValue] *12* [lblAgeExpectancy.text doubleValue];
Im just not familiar with Present Value/

Putting aside your code snippet for a little while, the present value calculation itself is reasonably straightforward, a least in its simpler forms. (It can become a fair bit more complicated if you start to consider more realistic interest with different rates at different terms and such, but if you want to get into that you'll need to do some proper reading up.)
The present value of any single future cash flow is the amount of money you would have to invest now (at the so-called risk-free rate) in order to have the future amount when the time comes. That is, it is the future amount discounted at the specified interest rate.
As a trivial example, suppose you are going to give me $105 in a year's time, and the annual interest rate is 5%. If I have $100 now and invest it at that rate, in a year's time I will have $105, the same amount you are due to give me. So the present value of that future $105 is not $105, but only $100. (This is just a slightly more formal equivalent of observing that a bird in the hand is worth two in the bush.)
Let's take a marginally more realistic example just to see how the calculation works. Suppose I'm due to receive $1000 in 5 years -- how much is that worth to me now?
Assume again that the relevant interest rate is 5% per year, and further assume that it is compounded annually -- which is to say, after a year the first 5% is added to the original amount and this combined amount then accrues interest over the second year, and so on. After each year I have the amount I started with the beginning plus the 5% interest on the amount -- that is 1.05 times what I started with at the beginning of the year. So after five years I would have 1.05 * 1.05 * 1.05 * 1.05 * 1.05 times as much as I had right at the beginning. To have $1000 in five years I would have to invest $1000 / 1.05 * 1.05 * 1.05 * 1.05 * 1.05, or about $784 -- and that's the present value of that $1000.
More generally, you would need to divide the future amount by pow(1 + r, n) for interest rate r and number of years n (or equivalently multiply by pow(1 + r, -n)), and there are simple generalizations for where the interest rate and payments are over different periods (eg, annual rate compounded monthly). See, eg, Wikipedia's compound interest entry for more detail.
OK, back to the question. Coding this calculation in Objective-C is no different from coding it in C. Again using the simple version described above:
double presentValue ( double futureValue, double annualRate, unsigned int years )
{
return futureValue * pow ( 1 + annualRate, -years );
}
You could do this as an Obj-C method rather than a C function, but the essence would be pretty similar. Adding more sophistication in terms of compounding periods and such is left as an exercise.
Note, however, that this doesn't bear very much resemblance to your own code, which looks to be just grabbing values blindly from text fields and multiplying them together. If you find yourself doing maths directly on the contents of views, you probably ought to be hearing alarm bells somewhere.
Not wishing to sound too high-horsey, but it seems to me that you need much more clearly to distinguish the underlying data (we could call it the model if we were being fancy) from the inputs (in other words, what is the user actually providing and what is the program expected to know how to do without them having to think about it). And furthermore, both these things should be considered separately from the UI elements used to represent them.
In other words, you probably need to revisit the whole Model-View-Controller pattern that every iPhone developer is supposed to have tattooed on their heart ;)

Related

Calculating IV60, and IV90 on interactive brokers

I am trading options, but I need to calculate the historical implied volatility in the last year. I am using Interactive Broker's TWS. Unfortunately they only calculate V30 (the implied volatility of the stock using options that will expire in 30 days). I need to calculate the implied volatility of the stock using options that will expire in 60 days, and 90 days.
The problem: Calculate the implied volatility of at least a whole year of an individual stock using options that will expire in 60 days and 90 days giving that:
TWS does not provide V60 or V90.
TWS does not provide historical pricing data for individual options for more than 3 months.
The attempted solution:
Use the V30 that TWS provide too come up with V60 and V90 giving the fact that usually option prices will behave like a skew (horizontal skew). However, the problem to this attempted solution is that the skew does not always have a positive slope, so I can't come up with a mathematical solution to always correctly estimate IV60 and IV90 as this can have a positive or negative slope like in the picture below.
Any ideas?
Your question is either confusing or isn't about programming. This is what IB says.
The IB 30-day volatility is the at-market volatility estimated for a
maturity thirty calendar days forward of the current trading day, and
is based on option prices from two consecutive expiration months.
It makes no sense to me and I can't even get those ticks to arrive (generic type 24). But even if you get them, they don't seem to be useful. My guess is it's an average to estimate what the IV would be for an option expiring exactly 30 days in the future. I can't imagine the purpose for this. The data would be impossible to trade with and doesn't represent reality. Imagine an earnings report at 29 or 31 days!
If you'd like the IV about 60 or 90 days in the future call reqMktData with an option contract that expires around then and an empty generic tick list. You will get tick types 10, 11, 12, and 13 which all have an IV. That's how you build the IV surface. If you'd like to build it with a weighted average to estimate 60 days, it's possible.
This is python but should be self explanatory
tickerId = 1
optCont = Contract()
optCont.m_localSymbol = "AAPL 170120C00130000"
optCont.m_exchange = "SMART"
optCont.m_currency = "USD"
optCont.m_secType = "OPT"
tws.reqMktData(tickerId, optCont, "", False)
Then I get data like
<tickOptionComputation tickerId=1, field=10, impliedVol=0.20363398519176756, delta=0.0186015418248492, optPrice=0.03999999910593033, pvDividend=0.0, gamma=0.007611155331932943, vega=0.012855970569816431, theta=-0.005936076573849303, undPrice=116.735001>
If there's something I'm missing about options, you should ask this at https://quant.stackexchange.com/

Negative option prices for certain input values in MATLAB?

In the course of testing an algorithm I computed option prices for random input values using the standard pricing function blsprice implemented in MATLAB's Financial Toolbox.
Surprisingly ( at least for me ) ,
the function seems to return negative option prices for certain combinations of input values.
As an example take the following:
> [Call,Put]=blsprice(67.6201,170.3190,0.0129,0.80,0.1277)
Call =-7.2942e-15
Put = 100.9502
If I change time to expiration to 0.79 or 0.81, the value becomes non-negative as I would expect.
Did anyone of you ever experience something similar and can come up with a short explanation why that happens?
I don't know which version of the Financial Toolbox you are using but for me (TB 2007b) it works fine.
When running:
[Call,Put]=blsprice(67.6201,170.3190,0.0129,0.80,0.1277)
I get the following:
Call = 9.3930e-016
Put = 100.9502
Which is indeed positive
Bit late but I have come across things like this before. The small negative value can be attributed to numerical rounding error and / or truncation error within the routine used to compute the cumulative normal distribution.
As you know computers are not perfect and small numerical error always persists in all calculations, in my view therefore the question one should must ask instead is - what is the accuracy of the input parameters being used and therefore what is the error tolerance for outputs.
The way I thought about it when I encountered it before was that, in finance, typical annual stock price return variance are of the order of 30% which means the mean returns are typically sampled with standard error of roughly 30% / sqrt(N) which is roughly of the order of +/- 1% assuming 2 years worth of data (so N = 260 x 2 = 520, any more data you have the other problem of stationarity assumption). Therefore on that basis the answer you got above could have been interpreted as zero given the error tolerance.
Also we typically work to penny / cent accuracy and again on that basis the answer you had could be interpreted as zero.
Just thought I'd give my 2c hope this is helpful in some ways if you are still checking for answers!

How to encourage optimiser to pick solution with fewest transactions (i.e. minimise cardinality)

I have a linear model that is seeking to move 'units' between 'cells' in an optimal manner. Each transfer costs $2 plus 1% of the unit amount transferred.
Lets say a target cell requires 100 units and can receive it from any of 10 source cells. How can I encourage the optimiser to make a single transfer of 100 units from one of the source cells (total cost 2+1) rather than transferring 10 units from each of the valid source cells (total cost 20+1)?
I've implemented this in matlab using mosek if it matters.
(Apologies if the question is a bit vague, this is all self-taught and I'm not sure how to ask this unambiguously with the correct terminology. Happy to repost this question on a more appropriate SE if there is one.)
This is a standard Integer programming called the Fixed Charge Transportation Problem.
Let's say that there are S suppliers and D customers with Demands.
Each supplier i has S_i units and each customer j has a Demand D_j
You need two types of decision variables.
Xij is the amount that goes from Supplier i to Customer j.
But there is a also the fixed cost that we have to take care of. Fij = 2 ($2 for each supplier that ships units.) Let the fixed cost variable be
Y_ij = 1 if Supplier i sends a non-zero number of units to Customer j.
Y_ij = 0 Otherwise.
Formulation
Objective Minimize sum of all Subsets.
Min sum (F_ij Yij) + sum Cij*Xij
Subject to:
Sum over i Xij >= D_j for each customer j //Demand satisfaction
Sum over j Xij <= S_i for each supplier i //Supply limitation
// if you use a supplier for a customer, Yij has to become 1.
Yij >= Xij for each i and each j
Yij binary, Xij >=0
You will find more on Fixed Charge Integer Programming problems in any standard OR textbook. Look for the chapter where Integer Programming is introduced.
Hope that helps you move forward.
the point is which is the objective function that you want to minimize or maximize. If you only want to reduce the number of transfer, you must minimize the number of non-zero transfers: assuming you have a variable $x_{ij}$ for the transfer from $i$ to $j$, then you should minimize $\sum y_{ij}$ where $y_{ij}$ is a binary variable that takes value $0$ when $x_{ij}=0$, $1$ otherwise.
I guess you can formulate the overall model as a min-cost flow between cells, possibly with additional constraints and with a non-trivial objective function.
(By the way, if you need help you might also contact us at mosek on our google forum...)

Simple algorithm modeling stock market behavior

I have been working on a virtual stock market game using PHP. The formula that I have been using for deciding the price of a stock is
$price += $ran*0.001*$price + $ratio*0.005*$price
where
$ran = rand(-1*$intensity, 2*$intensity)
$intensity is a number between -5 to 5 depending upon whether the news is good or bad for the company and
$ratio = (1.0*($buy-$sell))/($buy + $sell)
$buy and $sell represent the number of shares bought and sold of a company respectively.
The problem with this formula is that, even if the intensity is negative (even -5) the ratio term is always added to the price which makes the overall term increase. The prices are refreshed every 10 seconds and with the above formula they keep on increasing and never come down. So, can anyone help me out with this formula so that it varies more closely to the actual stock market?
If I understand correctly, you're trying to define an algorithm to determine a logical next price based on the current price, some market activity, and a random input. This is called a Random Walk, and the linked page is quite informative.
In economics, the "random walk hypothesis" is used to model shares prices and other factors. Empirical studies found some deviations from this theoretical model, especially in short term and long term correlations.
It's difficult for us to provide an exact function for you, since the exact behavior you expect of a function like this is inherently application specific. However it is possible to test the behavior and improve on it, by pulling it out into its own method and tweaking it until you see the behavior you want.
I would suggest pulling this behavior you've defined into an SSCCE (or a unit test, but assuming you don't already have a PHP unit test framework set up, an example will do fine) and creating some test cases, then you can tweak your algorithm in a vacuum and find behavior you like.
Here's some boilerplate to get started:
<?php
function nextPrice($price, $intensity, $buy, $sell, $rand) {
// TODO
}
// Can tweak these values between runs, or put them in a loop if you want
$testPrice = 10.0;
$testBuy = 10000;
$testSell = 10000;
for ($i = -5; $i <= 5; $i++) {
// random float, from http://stackoverflow.com/a/14155720/113632
// set to a constant if you want to isolate the randomness and test other variables
$testRand = mt_rand(0, mt_getrandmax() - 1) / mt_getrandmax();
echo "<p>Intensity: $i - Rand: $testRand = ".
nextPrice($testPrice, $i, $testBuy, $testSell, $testRand)."</p>";
}
?>
Some additional thoughts:
Your $ran definition is definitely flawed, if $intensity is -5 you're executing $ran = rand(5, -10); which generates a warning and doesn't return the value you want. This is likely the root of your issue, as any negative $intensity will essentially set $ran to zero.
Furthermore your $ran definition is biased towards positive numbers, meaning the price is - rather quickly - going to rise even if there's bad news. I'd suggest ensuring your random value is equally likely to lower the stock as raise it, and if you intend for the stock to rise in value over time regardless (which seems like a bad idea to me) set a separate $longTermGrowthFactor that always increases the stock by that factor, separately from the randomness.
Turn on warning reporting in PHP - since you presumably hadn't seen the warnings related to your rand() call, you likely have warnings and other error types turned off, which quite likely means there are other errors hidden in your code you aren't aware of, and without the reporting they're going to be hard to spot.
Use mt_rand() instead of rand(), the latter is deprecated, and mt_rand() is a drop-in replacement providing better randomness.

iPhone and floating point math

I have following code:
float totalSpent;
int intBudget;
float moneyLeft;
totalSpent += Amount;
moneyLeft = intBudget - totalSpent;
And this is how it looks in debugger: http://www.braginski.com/math.tiff
Why would moneyLeft calculated by the code above is .02 different compared to the expression calculated by the debugger?
Expression windows is correct, yet code above produces wrong by .02 result. It only happens for a very large numbers (yet way below int limit)
thanks
A single-precision float has 23 bits of precision. That means that every calculation is rounded to 23 binary digits. This means that if you have a computation that, say, adds a very small number to a very large number, rounding may result in strange results.
Imagine that you are doing math in scientific notation decimal by hand, under the rule that you may only have four significant figures. Let's say I ask you to write twelve in scientific notation, with four significant figures. Remembering junior high school, you write:
1.200 × 101
Now I say compute the square of 12, and then add 0.5. That is easy enough:
1.440×102 + 0.005×102 = 1.445×102
How about twelve cubed plus 0.75:
1.728×103 + 0.00075×103 = 1.72875×103
But remember, I only gave you room for four significant digits, so you must round; then we get:
1.728×103 + 7.5×10-1 = 1.729×103
See? The lack of precision can make the computation come out with unexpected results.
In your example, you've got 999999 in a calculation where you're trying to be precise to 0.01. log2(999999) = 19.93 and log2(0.01) = -6.64. The difference is more than 23; therefore you would need more than 23 binary digits to perform this calculation accurately.
Because floating point mathematics rounds-off precision by its very nature, it is usually a bad choice for currency computation, where you must be accurate to the last cent. But are you really concerned with fractions of a cent in your application? If not, then why not do away with the decimal point altogether, and simply store cents (instead of dollars) in a 64-bit integer? 264¢ is more than the GDP of the entire planet.
Floating point will always produce strange results with money type calculations.
The golden rule is that floating point is good for things you measure litres,yards,lightyears,bushels etc. etc. but not for things you count like
sheep, beans, buttons etc.
Most money calculations are to do with counting pennies so use integer math
and you wont get the strange results. Either use a fixed decimal arithimatic
library (which would probably be overkill on an iPhone) or store your amounts
as whole numbers of cents and only convert to $ and cents on display.