QQQ. First Trading Day of the month, open to close.

Profit/loss (%) calculated for each first trading day of the month for the period from 3/10/1999 till 11/28/2011: go long on open, exit on close.

year123456789101112Total
19990.000.000.00-0.82-0.23-2.090.36-0.440.091.39-0.531.04-1.23
2000-1.522.780.35-4.69-0.132.491.84-1.77-0.37-4.040.85-0.10-4.31
2001-9.580.933.76-4.743.841.11-0.441.09-2.94-0.442.54-0.83-5.70
20021.35-0.684.462.58-0.36-3.53-4.49-4.45-1.844.883.47-1.49-0.10
20032.67-0.13-2.490.040.90-1.692.13-0.731.111.640.930.524.90
2004-0.83-0.621.010.980.300.63-1.691.011.001.790.171.625.37
2005-1.490.080.69-1.710.060.94-0.360.03-0.210.050.161.18-0.58
20061.590.981.04-0.42-1.172.040.29-0.790.00-1.15-1.74-0.78-0.11
2007-0.50-0.611.36-0.190.31-0.300.661.071.501.06-1.25-0.422.69
2008-1.700.20-0.602.583.02-1.052.18-1.41-2.89-0.870.03-5.83-6.34
20094.142.15-1.802.710.301.73-0.450.43-1.55-2.670.320.285.59
20100.200.840.98-0.420.95-0.56-0.590.611.47-0.97-0.290.632.85
20110.621.11-2.07-0.45-0.34-1.991.44-1.68-1.18-1.76-0.140.00-6.44


Query used:
select [year], [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13] Total into #t
from
	(	select cast((t.c - t.o)/t.c * 100 as decimal(10,2)) pl, year(t.d) [year], MONTH(t.d) [month] 
		from qqq t
		join qqq t_1 on t_1.id = t.id - 1
		where month(t_1.d)%12 = MONTH(t.d) - 1)	p
pivot
(
sum(pl)
for [month] in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13]) 
)	r	
order by [year]


--2
update #t
set Total = coalesce([1], 0) + coalesce([2], 0) + coalesce([3], 0) + coalesce([4], 0) 
			+ coalesce([5], 0) + coalesce([6], 0) + coalesce([7], 0) + coalesce([8], 0) 
			+ coalesce([9], 0) + coalesce([10], 0) + coalesce([11], 0) + coalesce([12], 0) 

DECLARE @HeaderList varchar(max), @head varchar(1000)
SELECT @HeaderList = COALESCE(@HeaderList + '', '') +    name 
from tempdb.sys.columns where object_id = object_id('tempdb..#t') order by column_id
select @head = '' + @HeaderList + ''

DECLARE @SelectList varchar(max)
SELECT @SelectList = COALESCE(@SelectList + '+''''+', '') +    'CAST([' + name + '] AS varchar(50))'
from tempdb.sys.columns where object_id = object_id('tempdb..#t') order by column_id

declare @sql varchar(max)
select @sql = 'select ''' + @head + ''' union all select ''''+' + @SelectList + '+'''' from #t'
exec (@sql)


theCrunchR | © 2011