41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
|
# File 'lib/quandl/operation/transform.rb', line 41
def transform( data, type)
return data if data.blank?
type = type.try(:to_sym)
return data unless valid_transformation?( type )
temparr = Array.new
keylist = data.transpose.first
if keylist.count > 1
keylist = keylist.reverse if keylist[0] > keylist[1] keylist.sort!
end
numcols = data.first.size - 1
if type == :normalize
divisor = Array.new(numcols,nil)
0.upto(keylist.length - 1) do |i|
temparr[i] = []
curr_row = data[i][1..-1]
0.upto(numcols-1) do |x|
if curr_row[x].nil?
temparr[i][x] = nil
elsif divisor[x].nil?
if curr_row[x].to_f != 0
divisor[x] = curr_row[x].to_f
temparr[i][x] = 100.0
else
temparr[i][x] = 0
end
else
temparr[i][x] = curr_row[x] / divisor[x] * 100.0
end
end
end
0.upto(keylist.length-1) do |i|
data[i] = [keylist[i], temparr[i]].flatten
end
elsif [:diff, :rdiff].include? type
1.upto(keylist.length - 1) do |i|
temparr[i] = []
curr_row = data[i][1..-1]
prev_row = data[i-1][1..-1]
0.upto(numcols-1) do |x|
if type == :diff
if !curr_row[x].nil? and !prev_row[x].nil?
temparr[i][x] = Float(curr_row[x]) - Float(prev_row[x])
else
temparr[i][x] = nil
end
else
if !curr_row[x].nil? and !prev_row[x].nil? and prev_row[x] != 0
temparr[i][x] = ( Float(curr_row[x]) - Float(prev_row[x]) ) / Float( prev_row[x] )
else
temparr[i][x] = nil
end
end
end
end
1.upto(keylist.length-1) do |i|
data[i] = [keylist[i], temparr[i]].flatten
end
data.delete_at(0)
elsif type == :rdiff_from
num_rows = keylist.length - 1
initial = Array.new(numcols,nil)
num_rows.downto(0) do |i|
temparr[i] = []
curr_row = data[i][1..-1]
0.upto(numcols-1) do |x|
if curr_row[x].nil?
temparr[i][x] = nil
elsif initial[x].nil?
initial[x] = curr_row[x]
temparr[i][x] = 0.0
elsif curr_row[x] == 0
temparr[i][x] = nil
else
temparr[i][x] = ( Float(initial[x]) - Float(curr_row[x]) ) / Float(curr_row[x])
end
end
end
0.upto(keylist.length-1) do |i|
data[i] = [keylist[i], temparr[i]].flatten
end
else
cumulsum = Array.new(numcols,0)
sumstarted = Array.new(numcols,false)
0.upto(keylist.length - 1) do |i|
temparr[i] = []
curr_row = data[i][1..-1]
0.upto(numcols-1) do |x|
if !curr_row[x].nil?
cumulsum[x] = cumulsum[x] + curr_row[x]
sumstarted[x] = true
end
temparr[i][x] = cumulsum[x] if sumstarted[x]
end
end
0.upto(keylist.length-1) do |i|
data[i] = [keylist[i],temparr[i]].flatten
end
end
data
end
|