ねえ、クリス。すでに回答を受け入れていることは承知していますが、私が使用するソリューションを投稿すると思いました。うまくいけば、それは誰かに役立つでしょう。少なくとも、将来いつかそれを見つける場所を提供してくれます。:-)
これは、Excel 2007 コード モジュールから直接起動された VBA コードです。.Net に簡単に変換できます。
データ操作の鍵は、ピボット テーブル オブジェクトです。指定したレイアウトにデータを取り込むのに非常に効率的であることがわかりました。
Sub GetIndexData ()
Dim cn as ADODB.Connection, cmd As ADODB.Command, rs As ADODB.Recordset
Dim rPivotTopLeft As Range, rPivotBottomRight As Range
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'Get the data.'
Set cn = New ADODB.Connection
With cn
.Provider = "SQLOLEDB"
.ConnectionString = "Database=" & mDBName & ";" & _
"Server=" & mDBServerName & ";" & _
"UID=" & mDBUserID & ";" & _
"Password=" & mDBPassword & ";" & _
"Persist Security Info=True;"
.CursorLocation = adUseClient
.Open
End With
Set cmd = New ADODB.Command
Set rs = New ADODB.Recordset
With cmd
.ActiveConnection = adoTools.DBConnection
.CommandType = adCmdText
.CommandText = "SELECT YourData From YourSource WHERE YourCritera"
Set rs = .Execute
End With
If Not (rs.BOF And rs.EOF) Then 'Check that we have some data.'
'Put the data into a worksheet.'
With wsRawData
.Cells.CurrentRegion.Clear
Set rPivotTopLeft = .Range("A1")
With ThisWorkbook.PivotCaches.Add(SourceType:=xlExternal)
Set .Recordset = rs
.CreatePivotTable _
TableDestination:=rPivotTopLeft, _
TableName:="MyPivotTable"
End With
'Massage the data into the desired layout.'
With .PivotTables("MyPivotTable")
.ManualUpdate = True
.PivotFields("Date").Orientation = xlRowField
.PivotFields("Index").Orientation = xlColumnField
.AddDataField .PivotFields("Return"), "Returns", xlSum
.DisplayFieldCaptions = False
.ColumnGrand = False
.RowGrand = False
.ManualUpdate = False
End With
mMonthCount = Range(.Range("A3"), .Cells(Rows.Count, "A").End(xlUp)).Count
mIndexCount = Range(.Range("B2"), .Cells(2, Columns.Count).End(xlToLeft)).Count
'Convert pivot table to values.'
Set rPivotBottomRight = .Cells(mMonthCount + 2, mIndexCount + 1)
With .Range(rPivotTopLeft, rPivotBottomRight)
.Copy
.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End With
'Format the worksheet.'
.Range("A3").Resize(mMonthCount, 1).NumberFormat = "mmm-yy"
.Range("B3").Resize(mMonthCount, mIndexCount).NumberFormat = "0.00%"
Union(.Rows(2), .Columns(1)).Font.Bold = True
.Cells.ColumnWidth = 7.14
.Rows(1).Delete
End With
rs.close
Set rs = Nothing
cmd.ActiveConnection = Nothing
Set cmd = Nothing
cn.close
Set cn = Nothing
End Sub
そこから、組み込みの Excel 回帰統計を活用して相関行列を出力するのは比較的簡単です。この手法を使用すると、約 45 秒で 600x600 の相関行列を含むワークシートを作成できます。
.PivotFields パラメーターは、データ ソースのデータの列名に合わせて変更する必要があることに注意してください。