Hi Laurens,
Thanks, but my code is not really beautiful. What is beautiful and inspiring is that you are 84 years old and continuing to study and learn.
I will attempt to explain the last two lines of the code.
timeSeries = Entity["Financial", "NASDAQ:" <> ToUpperCase[symbol]][EntityProperty["Financial", property, dateRange]]
If symbol = "msft"
, the first part is
Entity["Financial", "NASDAQ:MSFT"]
Which is an Entity
of type Financial
and name NASDAQ:MSFT
. Entity documentation. For a list of all the available entity types evaluate
EntityValue[]
From an Entity
you can retrieve various properties. In this case we are interested in Financial properties. For a list of available Financial property names evaluate
EntityProperties["Financial"] // CanonicalName
The second part of that line is
[EntityProperty["Financial", property, dateRange]]
The property
is passed in as an argument to the financialData
function and dateRange
is constructed earlier in the function. It retrieves the specified property for the specified date range.
If we evaluate
property = "RawClose";
dateRange = {"Date" -> Interval[{DateObject[{2018, 11, 1}], DateObject[{2018, 11, 2}]}]};
timeSeries = Entity["Financial", "NASDAQ:MSFT"][EntityProperty["Financial", property, dateRange]]
We get a TimeSeries
The last line is
{DateValue[First[#], {"Year", "Month", "Day"}], QuantityMagnitude[Last[#]]} & /@ timeSeries["DatePath"]]
To get a list of date / value pairs we use the DatePath
property of the TimeSeries
. See documentation.
timeSeries["DatePath"]
Which evaluates to
Notice that the dates are DateObject
and not of the desired form of {YYYY, MM, DD}
and that the price is in units of USDollars
timeSeries["DatePath"] // First // First // FullForm
(* DateObject[List[2018,11,1,0,0,0.`],"Instant","Gregorian",-6.`] *)
timeSeries["DatePath"] // First // Last // FullForm
(* Quantity[105.92`,"USDollars"] *)
So we write a pure function to convert to the needed form and Map
it using /@
over the list of date / value pairs.
{DateValue[First[#], {"Year", "Month", "Day"}], QuantityMagnitude[Last[#]]} &
It converts DateObject
to {YYYY, MM, DD}
and gets the magnitude of the price without the USDollars
.
{DateValue[First[#], {"Year", "Month", "Day"}], QuantityMagnitude[Last[#]]} & /@ timeSeries["DatePath"]
(* {{{2018, 11, 1}, 105.92}, {{2018, 11, 2}, 106.16}} *)
I think Stephen Wolfram's book that you referenced covers most of the above.
See Entities, Map and /@, pure functions, more pure functions, units.
You should also take a look at this.
Hope that helps!.