Skip to content

Instantly share code, notes, and snippets.

@sguzman
Last active November 8, 2020 23:14
Show Gist options
  • Save sguzman/48d5eac03fc5c237475d2144faec9c35 to your computer and use it in GitHub Desktop.
Save sguzman/48d5eac03fc5c237475d2144faec9c35 to your computer and use it in GitHub Desktop.
Rank SP500 companies by industry and plot it
With[{
time = {{2020}},
ents = Table[
CompanyData[FinancialData[s, "Company"], "Industry"], {s,
Select[
EntityList[
EntityClass[
"Financial", {EntityProperty["Financial", "MarketCap"] ->
TakeLargest[100]}
]
],
Function[n,
And[
Not[MissingQ[FinancialData[n, "Company"]]],
Not[
MissingQ[
CompanyData[FinancialData[n, "Company"], "Industry"]]]
]
]
]
}
]
},
With[{
ts = Table[{
First[o],
TimeSeriesThread[
Function[f,
Total[
Map[
QuantityMagnitude, f]
]
],
Table[
FinancialData[l, "MarketCap", time],
{l, Last[o]}
]
]
}, {o,
Table[{
Last[First[o]],
Map[First, o]
}, {o,
Table[
GatherBy[{e,
e["Company"]["Industry"]},
Last],
{e, ents}
]
}
]
}
]
},
With[{all = TimeSeriesThread[Total, Map[Last, ts]]},
With[{
all2 = Table[{
First[t],
TimeSeriesThread[Apply[Divide], {Last[t], all}]
}, {t, ts}]},
With[{
fin = ReverseSortBy[all2, Function[m, Mean[Last[m]["Values"]]]]},
DateListPlot[
Map[Last, fin],
PlotRange -> Full,
PlotTheme -> "Marketing",
Joined -> False,
AspectRatio -> 1/3,
ImageSize -> Full,
PlotLegends -> Map[First, fin]]
]
]
]
]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment