0
$\begingroup$

This question already has an answer here:

I'm working on a project which analyzes financial data. I download the price and dividend information for the SPY ETF which tracks the S&P 500:

price = FinancialData["SPY", "RawClose", {"Jan 1, 2010", "July 31, 2015"}]
div = FinancialData["SPY", "Dividend", {"Jan 1, 2010", "July 31, 2015"}]

I want to find what the prices on the dividend dates were:

index = Position[price, p_ /; MemberQ[div[[All, 1]], p[[1]]], 1]

That gives the correct result. However it also give an error message:

Part::partd: Part specification List[[1]] is longer than depth of object.

How can I get rid of that?

$\endgroup$

marked as duplicate by Michael E2, m_goldberg, J. M. will be back soon Aug 2 '15 at 15:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 3
    $\begingroup$ Use Heads -> False, that is Position[price, p_ /; MemberQ[div[[All, 1]], p[[1]]], 1, Heads -> False] $\endgroup$ – kirma Aug 2 '15 at 13:51
3
$\begingroup$

Since kirma has pointed out the main trouble, which is also found in the potential duplicate Trouble with Position[], I thought I would add another alternative like Bob Brooks.

Comment:

Using Association here instead of lists to manage your data might be more convenient.

We can convert the data* either with

pa = Association[Rule @@@ price];
da = Association[Rule @@@ div];

or

pa = AssociationThread[Rule @@ Transpose@price];
da = AssociationThread[Rule @@ Transpose@div];

You can look up the prices on the dividend dates or create a new association as follows:

Lookup[pa, Keys[da]]
(*
  {115.97, 111.73, 112.49, 124.3, 127.76, 127.05, 121.52, 121.59, 
   140.3, 134.14, 145.87, 142.79, 155.83, 159.07, 170.72, 181.56, 186.2, 
   195.94, 200.7, 206.52, 210.41, 210.81}
*)

KeyTake[pa, Keys@da]
(*
  <|{2010, 3, 19} -> 115.97, {2010, 6, 18} -> 111.73, {2010, 9, 17} -> 112.49,
    ...some lines omitted...
    {2014, 12, 19} -> 206.52, {2015, 3, 20} -> 210.41, {2015, 6, 19} -> 210.81|>
*)

*Note: Execute

Rule @@@ div
Rule @@ Transpose@div

to see what these do. They restructure the lists into Rules that are used to associate a date with its corresponding value.

$\endgroup$
0
$\begingroup$

Zoff, Try this

Table[Cases[price, {div[[i, 1]], __}], {i, 1, Length[div]}]

This will give you the price on the dividend date instead of the position.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.