# before running the script:
# obtain price data in .csv format from ICAP allowance price explorer https://icapcarbonaction.com/en/ets-prices and save as icap.csv
# format numbers to "." instead of "," if necessary
# adjust directory
# check if column numbers in matplot and legend are still valid before running the script
fillnan=function(r){
x=0;v=NA;t=ets[,r]
while(x<length(t)) {
x=x+1
if (t[x]>0 | t[x]=='0') {t[x]=v=as.numeric(t[x])}
else {t[x]=v}}
ets[,r]<<-t}
ets=read.csv("c:\\source\\r\\icap.csv", header=TRUE,sep=";");
ets=ets[1184:length(ets[,1]),]
rows=c(3,59,72,85,98,111,20,33,46)
leg=c('EU-ETS','New Zealand','Kazakhstan','South Korea','Switzerland','RGGI (USA)','California','Quebec','Ontario','China max','China min')
chinarows=c(254,257,260,263,266,269,272,275)
for (x in c(rows,chinarows)){fillnan(x)}
svg(filename="ets-carbon-prices.svg", width = 8, height = 6, pointsize = 14, family = "sans", bg = "white", antialias = c("default", "none", "gray", "subpixel"))
par(mar=c(2.7,2.7,1,1)+0.1)
colors=1:11
linetypes=c(1,1,1,1,1,1,1,1,2,2,2)
chinapilots=(ets[,chinarows])
x=0
while (x<length(chinapilots[,1])) {
x=x+1;
a=apply(chinapilots[x,],1,as.numeric)
ets[x,4]=max(a,na.rm=TRUE)
ets[x,5]=min(a,na.rm=TRUE)}
fillnan(4);fillnan(5)
matplot(as.Date(ets[,1],format="%d.%m.%Y"), ets[,c(rows,4:5)],type="l",lwd=2,col=colors,lty=linetypes,main="ETS prices in €/tCO2")
legend("topleft",legend=leg,col=colors,lty=linetypes,cex=0.8)
axis(side=4, tck=0.01, las=0,tick=TRUE,labels = FALSE)
mtext(side=4,cex=0.75, line=0.05,R.version.string)
dev.off()