質問編集履歴

1

追記

2020/09/24 15:15

投稿

yuudai
yuudai

スコア65

test CHANGED
File without changes
test CHANGED
@@ -5,3 +5,331 @@
5
5
 
6
6
 
7
7
  そもそものやりたいことは、もともとあるデータフレーム(時系列データ)から新しくデータを作って元のデータとつなげたいのですが、その作ったデータが元のデータと長さが少し異なっていてどこでずれているかわからないのでmerge()で結合する際に'Time'という列をキーにしてつなげたいのです。また'Time'をリストにしてfor文で一行ずつ取り出したいです。データフレームのまま扱おうとすると列を指定したときにIndexError: string index out of rangeこのようなエラーが出るのでリストにしたいです。
8
+
9
+
10
+
11
+ サンプルコード
12
+
13
+
14
+
15
+ うまい説明の仕方がわからないのでコード全部乗っけます。
16
+
17
+
18
+
19
+ 時系列データのサンプルデータをどうやって用意すればいいかわかりませんがoandaapiでこのようなデータを用意します。
20
+
21
+ ![イメージ説明](683ffd1088a406ba6054ad9f31f7bd17.png)
22
+
23
+ ```ここに言語を入力
24
+
25
+ #トレンドラインを計算する
26
+
27
+ # 高値の始点/支点を取得
28
+
29
+ def get_highpoint(start, end):
30
+
31
+ chart = df[start:end+1]
32
+
33
+ while len(chart)>3:
34
+
35
+ regression = linregress(
36
+
37
+ x = chart['Time_ID'],
38
+
39
+ y = chart['High'],
40
+
41
+ )
42
+
43
+ chart = chart.loc[chart['High'] > regression[0] * chart['Time_ID'] + regression[1]]
44
+
45
+ return chart
46
+
47
+
48
+
49
+ # 安値の始点/支点を取得
50
+
51
+ def get_lowpoint(start, end):
52
+
53
+ chart = df[start:end+1]
54
+
55
+ while len(chart)>3:
56
+
57
+ regression = linregress(
58
+
59
+ x = chart['Time_ID'],
60
+
61
+ y = chart['Low'],
62
+
63
+ )
64
+
65
+ chart = chart.loc[chart['Low'] < regression[0] * chart['Time_ID'] + regression[1]]
66
+
67
+ return chart
68
+
69
+
70
+
71
+ def g_trendlines(span=240, min_interval=3):
72
+
73
+ trendlines = []
74
+
75
+ slope = [] # 傾き,リスト型
76
+
77
+ time = []
78
+
79
+
80
+
81
+ # 高値の下降トレンドラインを生成
82
+
83
+ for i in df.index[::span//2]:
84
+
85
+ highpoint = get_highpoint(i, i + span)
86
+
87
+ # ポイントが2箇所未満だとエラーになるので回避する
88
+
89
+ if len(highpoint) < 2:
90
+
91
+ continue
92
+
93
+ # 始点と支点が近過ぎたらトレンドラインとして引かない
94
+
95
+ if abs(highpoint.index[0] - highpoint.index[1]) < min_interval:
96
+
97
+ continue
98
+
99
+ regression = linregress(
100
+
101
+ x = highpoint['Time_ID'],
102
+
103
+ y = highpoint['High'],
104
+
105
+ )
106
+
107
+ print(regression[0] < 0.0, 'reg_high: ', regression[0], ', ', regression[1], )
108
+
109
+
110
+
111
+ # 下降してるときだけ
112
+
113
+ if regression[0] < 0.0:
114
+
115
+ trendlines.append(regression[0] * df['Time_ID'][i:i+span*2] + regression[1])
116
+
117
+ slope.append(regression[0] * df['Time_ID'][i:i+span*2])
118
+
119
+ time.append(df['Time'][i:i+span*2])
120
+
121
+
122
+
123
+ # 安値の上昇トレンドラインを生成
124
+
125
+ for i in df.index[::span//2]:
126
+
127
+ lowpoint = get_lowpoint(i, i + span)
128
+
129
+ # ポイントが2箇所未満だとエラーになるので回避する
130
+
131
+ if len(lowpoint) < 2:
132
+
133
+ continue
134
+
135
+ # 始点と支点が近過ぎたらトレンドラインとして引かない
136
+
137
+ if abs(lowpoint.index[0] - lowpoint.index[1]) < min_interval:
138
+
139
+ continue
140
+
141
+ regression = linregress(
142
+
143
+ x = lowpoint['Time_ID'],
144
+
145
+ y = lowpoint['Low'],
146
+
147
+ )
148
+
149
+ print(regression[0] > 0.0, 'reg_low: ', regression[0], ', ', regression[1], )
150
+
151
+
152
+
153
+ # 上昇してるときだけ
154
+
155
+ if regression[0] > 0.0:
156
+
157
+ trendlines.append(regression[0] * df['Time_ID'][i:i+span*2] + regression[1])
158
+
159
+ slope.append(regression[0] * df['Time_ID'][i:i+span*2])
160
+
161
+ time.append(df['Time'][i:i+span*2])
162
+
163
+
164
+
165
+ return trendlines, slope, time
166
+
167
+ ```
168
+
169
+
170
+
171
+ ![イメージ説明](020029d99dc77e7f030d5d91ebd02851.png)
172
+
173
+ along_time_dfの中身はこんな感じ
174
+
175
+ ```ここに言語を入力
176
+
177
+
178
+
179
+ #トレンドラインを計算する関数を実行。
180
+
181
+ #トレンドラインは同じ時間に複数重なっていることがあるのでdf['Close']に一番近い値を採用する
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+ #along_time_dfをどうにかしてリストにできれば解決できそう。そのほかの方法はわからない
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+ zaa, slope, along_time = g_trendlines()
198
+
199
+ df_intercept = pd.DataFrame(zaa)
200
+
201
+ df_slope = pd.DataFrame(slope)
202
+
203
+ along_time_df = pd.DataFrame(along_time)
204
+
205
+
206
+
207
+ df_intercept = df_intercept.transpose()
208
+
209
+ df_slope = df_slope.transpose()
210
+
211
+ along_time_df = along_time_df.transpose()
212
+
213
+
214
+
215
+ df_intercept = df_intercept.astype('float')
216
+
217
+ df_slope = df_slope.astype('float')
218
+
219
+
220
+
221
+ def getNearestValue(minimum, slope_dic):
222
+
223
+ """
224
+
225
+ 概要: 辞書から0に最も近い値を返却する関数
226
+
227
+ @return 0に最も近い値とそれに伴う傾き
228
+
229
+ """
230
+
231
+
232
+
233
+ calc_near_zero = min(minimum.items(), key=lambda x: x[1]) # 0に近い値を求める, the variable is tuple
234
+
235
+ key = calc_near_zero[0] #タプルの一つ目の要素を取得 , calc_near_zero = (key, value)
236
+
237
+ best_slope = slope_dic[key] # have just a value and トレンドラインの値と同じ列にある傾きを取得している
238
+
239
+ best_time = time_dic[key]
240
+
241
+ min_diff = calc_near_zero[1] # have just a value and calc_near_zero is tuple
242
+
243
+
244
+
245
+ return min_diff, best_slope, best_time
246
+
247
+
248
+
249
+
250
+
251
+ #トレードの判断をするときにトレンドラインが複数あると面倒なので一番近いトレンドラインと傾き(上昇or下降)を求めてdfに結合する
252
+
253
+ #データフレームのvalueだけをリスト形式で取り出さないとfor文で回せないので変換する
254
+
255
+ listdfi = df_intercept.values.tolist()
256
+
257
+ listdfs = df_slope.values.tolist()
258
+
259
+ listatd = along_time_df.values.tolist() #.values.tolist()これをやると全部NaNになってしまう
260
+
261
+ list_df_close = df['Close'][360:].values.tolist()
262
+
263
+
264
+
265
+ Near_trendline = []
266
+
267
+ slope_withTL = []
268
+
269
+ time_withtl = []
270
+
271
+
272
+
273
+ for i, dfi, dfs, atd in zip(list_df_close, listdfi, listdfs, along_time_df):
274
+
275
+ minimum = {}
276
+
277
+ slope_dic = {}
278
+
279
+ time_dic = {}
280
+
281
+ for c in range(35):
282
+
283
+ if dfi[c]:
284
+
285
+ diff = i - dfi[c] # 誤差を求める
286
+
287
+ slope = dfs[c] #slopeの値
288
+
289
+ tim = atd[c]
290
+
291
+ minimum[c] = abs(diff)
292
+
293
+ slope_dic[c] = slope
294
+
295
+ time_dic[c] = tim
296
+
297
+
298
+
299
+ best_TL, best_slope, best_time = getNearestValue(minimum, slope_dic)
300
+
301
+ Near_trendline.append(best_TL) #一番誤差が少ないdf_interceptの列を採用する
302
+
303
+ slope_withTL.append(best_slope)
304
+
305
+ time_withtl.append(best_time)
306
+
307
+
308
+
309
+
310
+
311
+ #slopeは上昇トレンドか下降トレンドかだけを知りたいので1,-1に変換する
312
+
313
+ slope_withTL = (1 if i >0 else -1 for i in slope_withTL)
314
+
315
+
316
+
317
+ #Near_trendlineとslope_withTLをデータフレームに変換する
318
+
319
+ df2 = pd.DataFrame({'Trend Line': Near_trendline,
320
+
321
+ 'Up or Down': slope_withTL,
322
+
323
+ 'Time': time_withtl
324
+
325
+ })
326
+
327
+
328
+
329
+
330
+
331
+ df3 = pd.merge(df, df2, on='Time', how='left')
332
+
333
+ ```
334
+
335
+ わかりにくくてすみません。