Skip to content

Instantly share code, notes, and snippets.

@ajoposor
Created May 26, 2017 17:14
Show Gist options
  • Select an option

  • Save ajoposor/d603cb2a41617bdaa340dd68274365ce to your computer and use it in GitHub Desktop.

Select an option

Save ajoposor/d603cb2a41617bdaa340dd68274365ce to your computer and use it in GitHub Desktop.
S&P Sectors full functionality - library use
<head>
<!-- Plotly.js -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/ajoposor/aoPlotlyAddOn/master/dist/aoPlotlyAddOn.min.js"></script>
<!-- jquery -->
<!-- <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>-->
</head>
<body>
<div id="wholeDiv_SP500_03" style="visibility:hidden">
<h3><font color="#1A5488"><b>S&P 500</b></font> sectors:<font color="#5AC148"><b>&#x25A0; C. Discretionary</b></font> - <font color="#CC0000"><b>&#x25A0; Energy</b></font> - <font color="#9845CE"><b>&#x25A0; Financials</b></font> - <font color="#FF9900"><b>&#x25A0; Industrials</b></font> - <font color="#FFCC00"><b>&#x25A0; Materials</b></font> - <font color="#FF3399"><b>&#x25A0; Real Estate</b></font> - <font color="#33FFFF"><b>&#x25A0; Technology</b></font> - <font color="#699966"><b>&#x25A0; Utilities</b></font></h3>
<div id="myDiv_SP500_03" class="plotly" align="left" style="width:100%; height:480px;"></div>
(*) Shaded areas indicate recessions.<br>For Real Estate: FRESX, Fidelity Real Estate<br>Data source: <a href="https://www.quandl.com">Quandl.</a>
</div>
<script>
<!-- JAVASCRIPT CODE GOES HERE -->
</script>
</body>

S&P Sectors full functionality - library use

S&P Sectors. Working on optional x axis aggregation (monthly, annual, daily), (average, end of period)

Y axis updates as plotted x axis range is changed.

Optional comparison. Traces recalculated to 1 at the beginning of the displayed range.

Recursive csv/json data reading so as to load all series as included in array.

Updated way to handle recessions.

Log or linear y axis.

A Pen by Antonio Osorio on CodePen.

License.

// THIS FIRST FUNCTION WOULD BE INCLUDED IN A DIV CODE TO SET A PLOT, THE REMAINER FUNCTIONS WILL BE ADDED TO THE https://rawgit.com/ajoposor/aoPlotlyAddOn/master/src/aoPlotlyAddOn.js LIBRARY
(function() {
// PARAMETERS: divInfo, series, options, timeInfo, layout
var divInfo = {
//whole div, including your titles and footnotes.
// required to hide div while plot loads.
wholeDivID: "wholeDiv_SP500_03",
// div in which plot will be included
// should be a div within 'wholeDiv'
plotDivID: "myDiv_SP500_03"
};
//X AXIS DATE RANGE PARAMETERS
var timeInfo = {
yearsToPlot: 1,
tracesInitialDate: "1998-12-31"
};
// URL PARAMETERS FOR TRACES TO BE READ
/* Source data to create data
provide one url for every trace. In case urlType = 'direct', make url = ''
Place urls for cvs files here and info about series, assumes one json/csv file per serie, or data directly provided in traceAttributes.
urlType can be 'csv', 'yqlJson', 'pureJson' or 'direct'
the yqlJson object is retured when the yql proxy is used, e.g:
var fredKey = 'FREDKEY';
var seriesId = 'UNRATE';
var seriesUnits ='lin';
var urlFred = 'https://api.stlouisfed.org/fred/series/observations?series_id='+seriesId+'&api_key='+fredKey+'&units='+seriesUnits+'&file_type=json';
var baseUri = "https://query.yahooapis.com/v1/public/yql?q=";
var uriQuery = encodeURIComponent("SELECT * from json where url='"+urlFred+"'");
url: baseUri + uriQuery+"&format=json";
the pureJson has only the observations
*/
//enter proxy roor 'url', if applicable, otherwise '';
var rootUrl = ""; //'http://kapitalvalue.com/quandl/quandl-proxy.php?timeout=60&url=';
var encodeSuffixUrl = false;
// enter your quandl api key
var yourQuandlApiKey = "L_MvzxJew8qq8_aXv_tx";
var directUrls = [
"https://www.quandl.com/api/v3/datasets/YAHOO/INDEX_GSPC.csv?api_key=" + yourQuandlApiKey,
//"https://www.quandl.com/api/v3/datasets/YAHOO/XLY.csv?api_key=" + yourQuandlApiKey,
"https://www.google.com/finance/historical?q=XLY&startdate=2001-12-31&output=csv",
"https://www.quandl.com/api/v3/datasets/YAHOO/XLE.csv?api_key=" + yourQuandlApiKey,
"https://www.quandl.com/api/v3/datasets/YAHOO/XLF.csv?api_key=" + yourQuandlApiKey,
"https://www.quandl.com/api/v3/datasets/YAHOO/XLI.csv?api_key=" +
yourQuandlApiKey,
"https://www.quandl.com/api/v3/datasets/YAHOO/XLB.csv?api_key=" +
yourQuandlApiKey,
"https://www.quandl.com/api/v3/datasets/YAHOO/FUND_FRESX.csv?api_key=" +
yourQuandlApiKey,
"https://www.quandl.com/api/v3/datasets/YAHOO/XLK.csv?api_key=" +
yourQuandlApiKey,
"https://www.quandl.com/api/v3/datasets/YAHOO/XLU.csv?api_key=" +
yourQuandlApiKey,
"https://www.quandl.com/api/v3/datasets/FRED/CPIAUCSL.csv?api_key="+
yourQuandlApiKey,
"https://www.quandl.com/api/v3/datasets/FRED/CPIAUCSL.csv?api_key="+
yourQuandlApiKey
];
function setUrls(rootUrl, directUrls) {
var urls = [];
for (var i = 0; i < directUrls.length; i++) {
if (encodeSuffixUrl) {
urls.push(rootUrl + encodeURIComponent(directUrls[i]));
} else {
urls.push(rootUrl + directUrls[i]);
}
}
return urls;
}
var urls = setUrls(rootUrl, directUrls);
// TRACE INFO
// use urlType = 'direct', 'csv' or 'yqlJson', 'pureJson'. In case 'direct, provide trace x and y arrays directly under traceAttriblutes
// xSeriesName and ySeriesName are the labels for each variable as they appear in the CSV or Json files.
// traceAttributes contains information in the same format a Plotly's trace, except for x and y which would be read from the csv or json files. Otherwise, provide x, and y arrays directly in traceAttributes.
var series = [
{
urlType: "csv",
url: urls[0],
xSeriesName: "Date",
ySeriesName: "Adjusted Close",
xDateSuffix: "",//"T00:00:00-04:00",
toggleRealNominal: true,
traceAttributes: {
type: "scatter",
name: "S&P 500",
mode: "lines",
opacity: 1,
fill: "tozeroy",
fillcolor: "rgba(205, 245,255, 0.20)", //#FAFCFD + 50% transparency
line: {
color: "#1A5488",
width: 3,
dash: "solid"
}
}
},
{
urlType: "yqlGoogleCSV",
url: urls[1],
xSeriesName: "Date",
ySeriesName: "Close",
xDateSuffix: "",//"T00:00:00-04:00",
toggleRealNominal: true,
traceAttributes: {
type: "scatter",
name: "C. Discretionary",
mode: "lines",
opacity: 0.8,
fill: "none",
fillcolor: "#5AC148",
line: {
color: "#5AC148",
width: 1,
dash: "solid"
}
}
},
{
urlType: "csv",
url: urls[2],
xSeriesName: "Date",
ySeriesName: "Adjusted Close",
xDateSuffix: "",//"T00:00:00-04:00",
toggleRealNominal: true,
traceAttributes: {
type: "scatter",
name: "Energy",
mode: "lines",
opacity: 0.8,
fill: "none",
fillcolor: "#5AC148",
line: {
color: "#CC0000",
width: 1,
dash: "solid"
}
}
},
{
urlType: "csv",
url: urls[3],
xSeriesName: "Date",
ySeriesName: "Adjusted Close",
xDateSuffix: "",//"T00:00:00-04:00",
toggleRealNominal: true,
traceAttributes: {
type: "scatter",
name: "Financials",
mode: "lines",
opacity: 0.8,
fill: "none",
fillcolor: "#5AC148",
line: {
color: "#9845CE",
width: 1,
dash: "solid"
}
}
},
{
urlType: "csv",
url: urls[4],
xSeriesName: "Date",
ySeriesName: "Adjusted Close",
xDateSuffix: "",//"T00:00:00-04:00",
toggleRealNominal: true,
traceAttributes: {
type: "scatter",
name: "Industrials",
mode: "lines",
opacity: 0.8,
fill: "none",
fillcolor: "#5AC148",
line: {
color: "#FF9900",
width: 1,
dash: "solid"
}
}
},
{
urlType: "csv",
url: urls[5],
xSeriesName: "Date",
ySeriesName: "Adjusted Close",
xDateSuffix: "",//"T00:00:00-04:00",
toggleRealNominal: true,
traceAttributes: {
type: "scatter",
name: "Materials",
mode: "lines",
opacity: 0.8,
fill: "none",
fillcolor: "#5AC148",
line: {
color: "#FFCC00",
width: 1,
dash: "solid"
}
}
},
{
urlType: "csv",
url: urls[6],
xSeriesName: "Date",
ySeriesName: "Close",
xDateSuffix: "",//"T00:00:00-04:00",
toggleRealNominal: true,
traceAttributes: {
type: "scatter",
name: "Real Estate",
mode: "lines",
opacity: 0.8,
fill: "none",
fillcolor: "#5AC148",
line: {
color: "#FF3399",
width: 1,
dash: "solid"
}
}
},
{
urlType: "csv",
url: urls[7],
xSeriesName: "Date",
ySeriesName: "Adjusted Close",
xDateSuffix: "",//"T00:00:00-04:00",
toggleRealNominal: true,
traceAttributes: {
type: "scatter",
name: "Technology",
mode: "lines",
opacity: 0.8,
fill: "none",
fillcolor: "#5AC148",
line: {
color: "#33FFFF",
width: 1,
dash: "solid"
}
}
},
{
urlType: "csv",
url: urls[8],
xSeriesName: "Date",
ySeriesName: "Adjusted Close",
xDateSuffix: "",//"T00:00:00-04:00",
toggleRealNominal: true,
traceAttributes: {
type: "scatter",
name: "Utilities",
mode: "lines",
opacity: 0.8,
fill: "none",
fillcolor: "#5AC148",
line: {
color: "#699966",
width: 1,
dash: "solid"
}
}
},{
urlType: "csv",
url: urls[9],
xSeriesName: "Date",
ySeriesName: "Value",
xDateSuffix: "",//"T00:00:00-04:00",
postProcessData: "end of month",
toggleRealNominal: true,
traceAttributes: {
type: "scatter",
visible: true,
name: "US CPI",
mode: "lines",
opacity: 0.8,
fill: "none",
fillcolor: "#5AC148",
line: {
color: "#000000",
width: 1,
dash: "dash"
}
}
},{
urlType: "csv",
url: urls[10],
xSeriesName: "Date",
ySeriesName: "Value",
xDateSuffix: "",//"T00:00:00-04:00",
deflactor: true,
toggleRealNominal: false,
postProcessData: "end of month",
traceAttributes: {
type: "scatter",
visible: false,
name: "US CPI",
mode: "lines",
opacity: 0.8,
fill: "none",
fillcolor: "#5AC148",
line: {
color: "#000000",
width: 1,
dash: "dash"
}
}
}
];
var settings = {
series: {
// frequency and aggregation info of base traces.
baseFrequency: "base", //could be 'daily', 'weekly', 'monthly', 'quarterly', 'annual' or your custom name.
baseAggregation: "close", // could be 'close', 'average', 'change', 'percChange', 'sqrPercChange', 'cumulative', or your custom name
targetFrequencyDisplay: "daily", //maximum frequency for display of x axis., could be monthly, quarterly, etc.
},
/*
// in case an initial change of frequency and aggregation is desired
changeFrequencyAggregationTo: {
frequency:'daily',
aggregation: 'close'
}
,*/
displayRecessions: true,
allowCompare: true,
allowDownload: true,
allowRealNominal: true,
initialRealNominal: "real", /*(could be set to "nominal" or "real")*/
baseRealDate: "end of range", /* could be "end of range", "end of domain", "beggining of range", beggining of domain", or a date "yyyy-mm-dd hh:mm:ss.sss-04:00"*/
downloadedFileName: "S&P Sectors Data",
xAxisNameOnCSV: "Date",
transformToBaseIndex: true, //series would be transformed to common value of 1 at beginning
allowFrequencyResampling: true, // includes buttons to allow for calculation of aggregation and methods (monthly, quarterly), close, average, etc.
desiredFrequencies: [
"daily",
"weekly",
"monthly",
"quarterly",
"semiannual",
"annual"
],
allowSelectorOptions: true, // buttons for time range selection, 3m, 6m, 1y, YTD, 5y, etc.
allowLogLinear: true,
textAndSpaceToTextRatio: 1.8,
endOfWeek: 5 // 0 Sunday, 1 Monday, etc.
};
var layout = {
yaxis: {
type: "log",
hoverformat: ".4r"
},
margin:{
r: 43
}
};
var options = {
showLink: false,
displayModeBar: false
};
aoPlotlyAddOn.newTimeseriesPlot(divInfo, series, settings, timeInfo, layout, options);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment