Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

dividend with recursive routine

by derpp (Acolyte)
on Aug 23, 2010 at 18:36 UTC ( [id://856784]=perlquestion: print w/replies, xml ) Need Help??

derpp has asked for the wisdom of the Perl Monks concerning the following question:

Hey monks,

So I want to be able to find the dividend from a stock. I've managed to do it in a simple way, but this time, I want to do it using a recursive routine. I can't seem to figure out how to do this. But anyway, here's the original script along with a few miserable attempts.

use warnings; print "A stock xyz's price is now $100. It has 3.78% dividend. You hav +e 1000 of it and reinvest the dividend into the stock.\n"; my %hash; @stocknum = 1000; @dividend = 6780; while ($#dividend != 20) { $a = $dividend[-1]; $stock = $stocknum[-1]; $div_total= $stock*100*0.0678; $stock_total = $stock + int($a/100); push (@stocknum, $stock_total); push (@dividend, $div_total); if ($#dividend == 20) { last; } } dividend (@dividend); sub dividend { @new = shift; $stock_num = $stocknum[-1]; $div = $stock_num*100*0.0678; push (@_, $div); @hash{@stocknum} = @_; foreach $key(sort keys %hash) { print "Stock number: $key\t"."Dividend: $hash{$key}\n"; } } $dividend=0.0378;
Thanks for the help in advance!

Replies are listed 'Best First'.
Re: dividend with recursive routine
by CountZero (Bishop) on Aug 23, 2010 at 18:51 UTC
    Why would you do such a thing? Just use the formula for compound interest:
    Future_value = present_value*(1 + interest_rate_per_period)**number_of +_periods

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      That formula assumes intermediate values can be non-integers. However, the OP wants to buy more shares with each years profit. And shares can only be bought as units. For instance, had the starting number of stock been 10 shares, it would have never increased, as the paid out yearly dividend would not have been enough to buy a new share.

      For the OPs values, a starting value of 1000, an interest of 6.78% and 20 years, your formula results in 3714 (rounded to nearest integer). But if you can only buy shares in units, you end up with 3696 shares. Close, but still 0.5% difference.

        Then I must have a better stockbroker than you, as I find partial shares in my account, which indeed automatically invests the dividends.

        CountZero

        A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      Yeah, but I wanna practice using recursive routines. Not working out so well, though.

        Define your problem in terms of itself:

        To calculate the total dividends received over N periods, calculate the total dividends received over the first N-1 periods, then add the dividends received in the Nth period.

        The rest should follow.

Re: dividend with recursive routine
by kennethk (Abbot) on Aug 23, 2010 at 20:13 UTC
    A few comments that I believe are very important about your posted code.
    1. The sequence $100 appears in your double-quote delimited string on line 2. Because double-quote delimited strings interpolate (Quote and Quote like Operators), Perl sees this as a variable. The variable $100 is the hundredth capture buffer from a regular expression. Had you actually tested what you posted, perl would have thrown a warning (Use of uninitialized value in concatenation (.) or string). You should not be posting code that throws warnings unless the warning pertains to your question. See How (Not) To Ask A Question.

    2. As we already discussed in counting number of occurrences of words in a file, why are you not using strict? If you opt not to use strict, why are you using my?

    3. You should never use $a as an ordinary variable. It has special meaning for sort. The only one-character variables which are socially acceptable to use as generic variables are $i, $j, $x, $y and $z, because these have established meanings that predate Perl (and microprocessors). Any time you use a variable with a single character for its name, you run a very real risk of clobbering some internal Perl behavior.

    4. Is your dividend 3.78% or 6.78%? Your code seems confused on that issue.

    5. Why do you create a hash and then sort the keys on your hash for output when you already have those keys in order in @stocknum? Why not just iterate over an index, or at least use the existing array as your list?

    6. Why do you concatenate two strings for your output? You are adding unnecessary operations, confusion and characters.

    7. Why do you have a floating $dividend variable at the end of your script, who's only function is to throw another pointless warning?

    8. Your indentation still leaves something to be desired. Check out perltidy as a way to make your code prettier.

    This code should probably not be written as a recursive from an efficiency standpoint - a for or while loop is pretty good, while of course the best way to do it is CountZero's exponentiation. However, that was your question and understanding how to build a recursive subroutine is good. For detailed explanations, I like the Recursion And Callbacks chapter from Higher-Order Perl, which is freely available for download. Post an attempt at a recursive subroutine, and we'll help you debug it. Please note that writing recursive subroutines without strict nearly always results in bugs. Good luck.
Re: dividend with recursive routine
by JavaFan (Canon) on Aug 23, 2010 at 21:15 UTC
    Untested:
    my $SHARES = 1000; my $DIVIDEND = 0.0678; my $YEARS = 20; sub stock { my ($shares, $years) = @_; $years >= 1 ? stock(int($shares * (1 + $DIVIDEND)), $years - 1) : +$shares; } print stock $SHARES, $YEARS;
Re: dividend with recursive routine
by BioLion (Curate) on Aug 23, 2010 at 18:52 UTC

    This is a job for *subroutines(wo|man)*!! Sorry I don't have time to give you a proper answer, but check out perlsub and read up on subroutines (i.e. recursively used 'functions', such as your dividend calculator) - the important bit is passing info in and out.

    Hope this helps, and sorry for the brief answer...

    Just a something something...
Re: dividend with recursive routine
by dHarry (Abbot) on Aug 24, 2010 at 09:33 UTC

    Some general points about investing & the reinvestment of dividends with respect to the model you use (nothing to do with Perl).

  • stock prices are not constant, it might be $100 right now but how about 3 years from now?
  • dividend is not constant, typically you would like to see dividend go up over time:)
  • reinvestment of dividend... "cash is king!" Personally I don't reinvest dividends (in the same stock) unless I get something extra out of it, like a DRIP but only when it offers me some additional advantage. I would like to decide for myself at what price I buy a stock!
  • CountZero raises an interesting point, some brokers allow you to buy fractions of shares, not just mutual funds but of specific stocks as well.
  • So I suggest to complicate things:)

  • Model the volatility of the stock and the (slight) increase of dividends over time.
  • Maybe factor in the buying of fractions of stocks?
  • A bare number some years from now doesn't mean anything, if you want a more meaningful number you will have to take into account costs (your broker), taxes (sigh) and inflation.
  • Cheers,

    Harry

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://856784]
Approved by BioLion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-25 08:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found