Module: Tushare::Stock::Trading

Extended by:
Util
Defined in:
lib/tushare/stock/trading.rb

Class Method Summary collapse

Methods included from Util

_code_to_symbol, _write_console, _write_head, check_quarter, check_year, fetch_ftp_file, holiday?, trade_cal

Class Method Details

._get_index_url(index, code, qt) ⇒ Object



542
543
544
545
546
547
548
549
550
# File 'lib/tushare/stock/trading.rb', line 542

def _get_index_url(index, code, qt)
  if index
    format(HIST_INDEX_URL, P_TYPE['http'], DOMAINS['vsf'], code, qt[0],
           qt[1])
  else
    format(HIST_FQ_URL, P_TYPE['http'], DOMAINS['vsf'], code, qt[0],
           qt[1])
  end
end

._get_k_data(url, dataflag = '', symbol = '', code = '', index = false, ktype = '') ⇒ Object



481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# File 'lib/tushare/stock/trading.rb', line 481

def _get_k_data(url, dataflag = '', symbol = '', code = '', index = false, ktype = '')
  response = HTTParty.get(url)
  return [] if response.length < 100
  response = response.split('=')[1]
  response.gsub!(/,{"nd.*?}/, '')
  js = JSON.parse(response)
  dataflag = js['data'][symbol].keys.include?(dataflag) ? dataflag : TT_K_TYPE[ktype.upcase]
  return [] if js['data'][symbol][dataflag].length == 0
  data = []
  cols = KLINE_TT_COLS
  if (js['data'][symbol][dataflag][0].length) == 6
    cols = KLINE_TT_COLS_MINS
  end
  js['data'][symbol][dataflag].each do |datum|
    object = { 'code' => index ? symbol : code }
    datum.each_with_index do |v, i|
      if (cols[i] != 'date')
        object[cols[i]] = v.to_f
      else
        object[cols[i]] = v
      end
    end
    data.push(object)
  end
  data
end

._parse_fq_data(url, index) ⇒ Object



527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'lib/tushare/stock/trading.rb', line 527

def _parse_fq_data(url, index)
  html = Nokogiri::HTML(open(url), nil, 'gbk')
  columns = index ? HIST_FQ_COLS[0..7] : HIST_FQ_COLS
  result = []
  html.css('table#FundHoldSharesTable tr').drop(2).each do |tr|
    object = {}
    tr.css('td').each_with_index do |td, i|
      next if columns[i].nil?
      object[columns[i]] = td.text.strip
    end
    result << object
  end
  result
end

._parse_fq_factor(code, start_date, end_date) ⇒ Object



508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# File 'lib/tushare/stock/trading.rb', line 508

def _parse_fq_factor(code, start_date, end_date)
  symbol = _code_to_symbol(code)
  url = format(HIST_FQ_FACTOR_URL, P_TYPE['http'], DOMAINS['vsf'],
               symbol)
  resp = HTTParty.get(url)
  string = resp.body[1..-2].gsub('{_', '{"')
                           .gsub!('total', '"total"')
                           .gsub!('data', '"data"')
                           .gsub!(':"', '":"')
                           .gsub!('",_', '","')
                           .tr!('_', '-')
  json = JSON.parse(string)
  result = []
  json['data'].each_pair do |key, value|
    result << { 'date' => key, 'factor' => value.to_f }
  end
  result.uniq { |object| object['date'] }
end

._parsing_dayprice_json(pageNum = 1) ⇒ Object

”‘

       


572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/tushare/stock/trading.rb', line 572

def _parsing_dayprice_json(pageNum = 1)
  _write_console
  url = format(SINA_DAY_PRICE_URL, P_TYPE['http'], DOMAINS['vsf'], PAGES['jv'], pageNum)

  resp = HTTParty.get(url)
  if resp.code.to_s == '200'
    val = resp.body.encode('utf-8', 'gbk')
    return nil if val == 'null'
    hs   = eval(val)
    cols = DAY_TRADING_COLUMNS.clone
    cols.delete('symbol')
    hs.map { |x| t = {}; cols.each { |c| t[c.to_sym] = x[c.to_sym] };  t }

  else
    nil
  end
end

._random(n = 13) ⇒ Object



597
598
599
600
601
# File 'lib/tushare/stock/trading.rb', line 597

def _random(n = 13)
  start_int = 10 ** (n - 1)
  end_int = (10 ** n) -1
  rand(start_int..end_int).to_s
end

._today_ticks(symbol, tdate, pageNo, ticks) ⇒ Object



552
553
554
555
556
557
558
559
560
561
562
# File 'lib/tushare/stock/trading.rb', line 552

def _today_ticks(symbol, tdate, pageNo, ticks)
  url = format(TODAY_TICKS_URL, P_TYPE['http'], DOMAINS['vsf'], PAGES['t_ticks'], symbol, tdate, pageNo)
  doc = Nokogiri::HTML(open(url), nil, 'gbk')
  doc.css('table#datatbl > tbody > tr').each do |tr|
    items = []
    tr.children.each do |td|
      items << td.content.gsub(/\s+/, '').gsub('--', '0').gsub('%', '')
    end
    ticks << Hash[TODAY_TICK_COLUMNS.zip(items)] unless items.empty?
  end
end

.code_to_symbol(code) ⇒ Object



590
591
592
593
594
595
# File 'lib/tushare/stock/trading.rb', line 590

def code_to_symbol(code)
  return INDEX_LIST[code] if INDEX_LABELS.include? code
  return '' if code.length != 6
  return "sh#{code}" if %w(5 6 9).include? code[0]
  return "sz#{code}"
end

.get_h_data(code, start_date = nil, end_date = nil, autype = 'qfq', index = false, drop_factor = true) ⇒ Object

获取历史复权数据Parameters


code:string
            

return


DataFrame
    date 


273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/tushare/stock/trading.rb', line 273

def get_h_data(code, start_date = nil, end_date = nil, autype = 'qfq',
               index = false, drop_factor = true)
  start_date = if start_date.nil?
                 Date.today.prev_year
               else
                 Date.strptime(start_date, '%F')
               end
  end_date = if end_date.nil?
               Date.today
             else
               Date.strptime(end_date, '%F')
             end
  qs = start_date.step(end_date)
                 .map { |d| [d.year, (d.month + 2) / 3] }
                 .uniq
  _write_head
  result = _parse_fq_data(_get_index_url(index, code, qs[0]), index)
  if qs.length > 1
    1.upto(qs.length - 1).each do |i|
      _write_console
      result.concat _parse_fq_data(_get_index_url(index, code, qs[i]),
                                   index)
    end
  end
  return [] if result.empty?
  sorted_result = result.sort_by { |object| Date.strptime(object['date'], '%F') }
  last_date = sorted_result.last['date']
  result = result.uniq { |object| object['date'] }.select do |object|
    date = Date.strptime(object['date'], '%F')
    date >= start_date && date <= end_date
  end
  if index
    return result.sort_by { |object| Date.strptime(object['date'], '%F') }
  end
  # 判断复权
  if autype == 'hfq'
    result.map do |object|
      object.delete 'factor' if drop_factor
      %w(open high close low).each do |key|
        object[key] = object[key].to_f.round(2)
      end
    end
    if index
      return result.sort_by { |object| Date.strptime(object['date'], '%F') }
    end
    result
  elsif autype == 'qfq'
    result.map { |object| object.delete 'factor' } if drop_factor
    fq_factors = _parse_fq_factor(code, start_date, end_date)
    fq_factors.sort_by! { |object| Date.strptime(object['date'], '%F') }
    frow = fq_factors.select { |object| object['date'] == last_date }.first
    rt = get_realtime_quotes(code)
    return nil if rt.empty?
    pre_close = if rt.first['high'].to_f == 0 && rt.first['low'].to_f == 0
                  rt.first['pre_close'].to_f
                elsif holiday? Date.today
                  rt.first['price'].to_f
                elsif Time.now.hour > 9 && Time.now.hour < 18
                  rt.first['pre_close'].to_f
                else
                  rt.first['price'].to_f
                end
    rate = frow['factor'].to_f / pre_close
    result.each do |object|
      %w(open high low close).each do |key|
        object[key] = (object[key].to_f / rate).round(2)
      end
    end
    result.sort_by { |object| Date.strptime(object['date'], '%F') }
  else
    result.each do |object|
      %w(open high low close).each do |key|
        object[key] = (object[key].to_f / object['factor'].to_f).round(2)
      end
      object.delete 'factor' if drop_factor
    end
    result.sort_by { |object| Date.strptime(object['date'], '%F') }
  end
end

.get_hist_data(code, options = {}) ⇒ Object

获取个股历史交易记录

Parameters
------
  code:string
              


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
# File 'lib/tushare/stock/trading.rb', line 25

def get_hist_data(code, options = {})

  symbol_code = _code_to_symbol(code)

  raise 'invalid code' if symbol_code == ''

  options = { start_date: '', end_date: '', ktype: 'D', ascending: false }.merge(options)

  if K_LABELS.include?(options[:ktype].upcase)
    url = format(DAY_PRICE_URL,
                 P_TYPE['http'],
                 DOMAINS['ifeng'],
                 K_TYPE[options[:ktype].upcase],
                 symbol_code)
  elsif K_MIN_LABELS.include?(options[:ktype])
    url = format(DAY_PRICE_MIN_URL,
                 P_TYPE['http'],
                 DOMAINS['ifeng'],
                 symbol_code,
                 options[:ktype])
  else
    raise 'ktype input error.'
  end

  cols = INDEX_LABELS.include?(code) ? INX_DAY_PRICE_COLUMNS : DAY_PRICE_COLUMNS

  resp = HTTParty.get(url)
  if resp.code.to_s == '200'
    records = JSON.parse(resp.body)['record']
    unless records.empty?
      cols = INX_DAY_PRICE_COLUMNS if records.first.size == 14

      records.reverse! if options[:ascending] == false
      if options[:start_date] != '' && options[:end_date] != ''
        records = records.select { |x| Time.parse(x[0]) <= Time.parse("#{options[:end_date]} 23:59") && Time.parse(x[0]) >= Time.parse("#{options[:start_date]} 00:00") }
      end

      records.map { |r| Hash[cols.zip(r)] }
    end
  else
    []
  end
end

.get_hists(symbols, start_date: '', end_date: '', ktype: 'D') ⇒ Object



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/tushare/stock/trading.rb', line 392

def get_hists(symbols, start_date: '', end_date: '', ktype: 'D')
  if  symbols.respond_to? :each
    result = []
    symbols.each do |symbol|
      data = get_hist_data(symbol, start_date: start_date,
                                   end_date: end_date,
                                   ktype: ktype)
      data.map { |object| object['code'] = symbol }
      result.concat data
    end
    result
  else
    nil
  end
end

.get_indexObject

获取大盘指数行情return


DataFrame
    code:


367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/tushare/stock/trading.rb', line 367

def get_index
  url = format(INDEX_HQ_URL, P_TYPE['http'], DOMAINS['sinahq'])
  resp = HTTParty.get(url)
  string = resp.body.encode('utf-8', 'gbk')
               .delete('var hq_str_sh')
               .delete('var hq_str_sz')
               .delete('";')
               .delete('"')
               .tr!('=', ',')
  csv = CSV.new(string)
  result = []
  headers = INDEX_HEADER.split(',')
  csv.each do |row|
    object = {}
    row.each_with_index do |value, index|
      next unless INDEX_COLS.include? headers[index]
      object[headers[index]] = value
    end
    object['change'] = ((object['close'].to_f / object['preclose'].to_f - 1) * 100).round(2)
    object['amount'] = (object['amount'].to_f / 100_000_000).round(4)
    result << object
  end
  result
end

.get_k_data(code = nil, start_date = '', end_date = '', ktype = 'D', autype = 'qfq', index = false) ⇒ Object

获取k线数据


Parameters:

code:string
            

return


DataFrame
    date 


437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/tushare/stock/trading.rb', line 437

def get_k_data(code = nil, start_date = '', end_date = '', ktype = 'D', autype = 'qfq', index = false)
  symbol = index ? INDEX_SYMBOL[code] : _code_to_symbol(code)
  dataflag = ''
  autype = autype.nil? ? '' : autype
  if !start_date.nil? && start_date != ''
    end_date = end_date.nil? || end_date == '' ? Date.today.strftime('%Y-%m-%d') : end_date
  end
  if K_LABELS.include?(ktype.upcase)
    fq = !autype.nil? ? autype : ''
    fq = '' if %w(1 5).include?(code[0]) || index
    kline = autype.nil? ? '' : 'fq'
    if (start_date.nil? || start_date == '') && (end_date.nil? || end_date == '')
      urls = [format(KLINE_TT_URL, P_TYPE['http'], DOMAINS['tt'], kline, fq, symbol, TT_K_TYPE[ktype.upcase], start_date, end_date, fq, _random(17))]
    else
      years = tt_dates(start_date, end_date)
      urls = []
      years.each do |year|
        urls.push(format(KLINE_TT_URL, P_TYPE['http'], DOMAINS['tt'], kline, "#{fq}#{year}", symbol, TT_K_TYPE[ktype.upcase], "#{year}-01-01", "#{year + 1}-12-31", fq, _random(17)))
      end
    end
    dataflag = format('%s%s', fq, TT_K_TYPE[ktype.upcase])
  elsif K_MIN_LABELS.include?(ktype)
    urls = [format(KLINE_TT_MIN_URL, P_TYPE['http'], DOMAINS['tt'], symbol, ktype, ktype, _random(16))]
    dataflag = format('m%s', ktype)
  else
    throw TypeError.new('ktype input error.')
  end
  data = []
  urls.each do |url|
    data = data.concat(_get_k_data(url, dataflag, symbol, code, index, ktype))
  end
  if !K_MIN_LABELS.include?(ktype) && (!start_date.nil? && start_date != '') && (!end_date.nil? && end_date != '') && !data.empty?
    start_date = Date.strptime(start_date, '%Y-%m-%d')
    end_date = Date.strptime(end_date, '%Y-%m-%d')
    data.select! do |datum|
      date = Date.strptime(datum['date'], '%Y-%m-%d')
      start_date <= date && date <= end_date
    end
  end
  data
end

.get_realtime_quotes(symbols = nil) ⇒ Object

获取实时交易数据 getting real time quotes data 用于跟踪交易情况(本次执行的结果-上一次执行的数据)Parameters


symbols : string, array-like object (list, tuple, Series).

return


DataFrame 


229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/tushare/stock/trading.rb', line 229

def get_realtime_quotes(symbols = nil)
  symbols = [symbols] if symbols.is_a?(String)
  symbols_list = (symbols || []).map { |code| code_to_symbol(code) }
                                .join(',')
  url = format(LIVE_DATA_URL, P_TYPE['http'], DOMAINS['sinahq'],
               _random, symbols_list)
  resp = HTTParty.get(url)
  resp_string = resp.body.encode('utf-8', 'gbk')
  result = []
  resp_string.scan(/\="(.*)";/).each_with_index do |match_array, match_index|
    string = match_array.first
    object = { 'code' => symbols[match_index] }
    string.split(',').each_with_index do |s, index|
      next if LIVE_DATA_COLS[index] == 's'
      object[LIVE_DATA_COLS[index]] = s
    end
    result << object
  end
  result
end

.get_sina_dd(code, options = {}) ⇒ Object

”‘

    


115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/tushare/stock/trading.rb', line 115

def get_sina_dd(code, options = {})
  return nil if code.nil? || code.size != 6
  symbol_code = _code_to_symbol(code)
  raise 'invalid code' if symbol_code == ''

  options = { date: Time.now.strftime('%Y-%m-%d'), vol: 400 }.merge(options)

  vol = options[:vol] * 100
  url = format(SINA_DD, P_TYPE['http'], DOMAINS['vsf'], PAGES['sinadd'], symbol_code, vol, options[:date])
  resp = HTTParty.get(url)
  if resp.code.to_s == '200'
    val = resp.body.encode('utf-8', 'gbk')
    CSV.new(val, headers: :first_row, encoding: 'utf-8', col_sep: ',').map do |a|
      fields = a.fields
      fields[0] = fields[0][2..-1]
      Hash[SINA_DD_COLS.zip(fields)]
    end
  else
    []
  end
end

.get_tick_data(code, date = '') ⇒ Object

”‘

    


81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/tushare/stock/trading.rb', line 81

def get_tick_data(code, date = '')
  return nil if code.nil? || code.size != 6 || date == ''

  symbol_code = _code_to_symbol(code)

  raise 'invalid code' if symbol_code == ''

  url = format(TICK_PRICE_URL, P_TYPE['http'], DOMAINS['sf'], PAGES['dl'], date, symbol_code)

  resp = HTTParty.get(url)
  if resp.code.to_s == '200'
    tb_value = resp.body.encode('utf-8', 'gbk')
    CSV.new(tb_value, headers: :first_row, encoding: 'utf-8', col_sep: ' ').map { |a| Hash[TICK_COLUMNS.zip(a.fields)] }
  else
    []
  end
end

.get_today_allObject

”‘

    


181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/tushare/stock/trading.rb', line 181

def get_today_all
  _write_head
  all_data = []
  data = _parsing_dayprice_json(1)
  unless data.nil?
    all_data << data
    (2...PAGE_NUM[0]).each do |page|
      nd = _parsing_dayprice_json(page)
      all_data << nd unless nd.nil?
    end
    all_data.flatten!
  end
  all_data
end

.get_today_ticks(code) ⇒ Object

”‘

    


151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/tushare/stock/trading.rb', line 151

def get_today_ticks(code)
  return nil if code.nil? || code.size != 6
  symbol_code = _code_to_symbol(code)
  raise 'invalid code' if symbol_code == ''

  all_ticks = []

  url = format(TODAY_TICKS_PAGE_URL, P_TYPE['http'], DOMAINS['vsf'], PAGES['jv'], Time.now.strftime('%Y-%m-%d'), symbol_code)
  resp = HTTParty.get(url)
  if resp.code.to_s == '200'
    val = eval(resp.body[1..-2])
    pages = val[:detailPages].sort { |x, y| x[:page] <=> y[:page] }
    date  = Time.now.strftime('%Y-%m-%d')
    _write_head
    pages.each do |page|
      _write_console
      _today_ticks(symbol_code, date, page[:page], all_ticks)
    end
    all_ticks
  else
    []
  end
end

.tt_dates(start_date = '', end_date = '') ⇒ Object



603
604
605
606
607
# File 'lib/tushare/stock/trading.rb', line 603

def tt_dates(start_date = '', end_date = '')
  start_year = start_date[0...4].to_i
  end_year = end_date[0...4].to_i
  (start_year..(end_year + 1)).step(2).to_a
end