/
mssql.php
4747 lines (4285 loc) · 151 KB
/
mssql.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
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
478
479
480
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* 货币基金都从网页抓,货币基金波动很小
*/
class mssql
{
private static $mssql;
private static $data; //拆分分红存储
function __construct($router)
{
$work=implode('-',$router);
self::log("{$work} Work Start !!!",true);
}
private static function getDb()
{
if(!self::$mssql)
{
$options=array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,PDO::ATTR_TIMEOUT=>3);
if(DIRECTORY_SEPARATOR=='/')
{
//linux
self::$mssql=new PDO("odbc:Driver=SQLNativeClient;Server=10.4.27.179;Database=GTA_QIA_QDB;Uid=funddev;Pwd=123456789Aa;",'funddev','123456789Aa',$options);
}
else
{
//windows
self::$mssql=new PDO("odbc:Driver={SQL Server};Server=10.4.27.179;Database=GTA_QIA_QDB;",'funddev','123456789Aa',$options);
}
}
return self::$mssql;
}
private static function runSql($sql)
{
try
{
return self::getDb()->exec($sql);
}
catch (PDOException $e)
{
// wangyu test start
//self::log("Error in runsql $e->getMessage()");
// wangyu test end
return app::Error(500,"Run Sql [ {$sql} ] Error : ".$e->getMessage());
}
}
private static function getData($sql)
{
try
{
$rs=self::getDb()->query($sql);
return $rs===false?array():$rs->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $e)
{
return app::Error(500,"Run Sql [ {$sql} ] Error : ".$e->getMessage());
}
}
private static function getLine($sql)
{
try
{
$rs=self::getDb()->query($sql);
return $rs===false?array():$rs->fetch(PDO::FETCH_ASSOC);
}
catch (PDOException $e)
{
return app::Error(500,"Run Sql [ {$sql} ] Error : ".$e->getMessage());
}
}
private static function getVar($sql)
{
try
{
$rs=self::getDb()->query($sql);
return $rs===false?null:$rs->fetchColumn();
}
catch (PDOException $e)
{
return app::Error(500,"Run Sql [ {$sql} ] Error : ".$e->getMessage());
}
}
private static function log($msg,$writeFile=false)
{
echo date('H:i:s').' '.$msg.PHP_EOL;
if($writeFile)
{
file_put_contents(date('Y-m-d').'-run.log',date('Y-m-d H:i:s').' '.$msg.PHP_EOL,FILE_APPEND);
}
}
private static function getRootDb()
{
if(!self::$mssql)
{
$options=array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,PDO::ATTR_TIMEOUT=>3);
if(DIRECTORY_SEPARATOR=='/')
{
//linux
self::$mssql=new PDO("odbc:Driver=SQLNativeClient;Server=10.4.27.179;Database=GTA_QIA_QDB;Uid=sa;Pwd=123456789Aa;",'sa','123456789Aa',$options);
}
else
{
//windows
self::$mssql=new PDO("odbc:Driver={SQL Server};Server=10.4.27.179;Database=GTA_QIA_QDB;",'sa','123456789Aa',$options);
}
}
return self::$mssql;
}
private static function runRootSql($sql)
{
try
{
return self::getRootDb()->exec($sql);
}
catch (PDOException $e)
{
return app::Error(500,"Run Sql [ {$sql} ] Error : ".$e->getMessage());
}
}
// get max id for target table in mysql
private static function get_max_id($table_name, $id_name) {
#$sql = "SELECT top 1 $id_name FROM $table_name ORDER BY $id_name desc";
$sql = "SELECT `{$id_name}` FROM `{$table_name}` ORDER BY `{$id_name}` desc limit 1";
$id_array = DB::getData($sql);
if (count($id_array) > 0) {
$max_id = (int) ($id_array[0][$id_name]);
} else {
$max_id = -1;
}
return $max_id;
}
// get row count for target table in mysql
private static function get_row_count($table_name) {
$sql = "SELECT count(*) FROM $table_name ";
$ret = DB::getData($sql);
$count = (int) ($ret[0]["count(*)"]);
return $count;
}
// get row count for target table in sql server
private static function get_ms_row_count($table_name, $addtion_where = null) {
$sql = "SELECT count(*) FROM [dbo].[{$table_name}] ";
if ($addtion_where != null) {
$sql = $sql." where {$addtion_where}";
}
var_dump($sql);
$ret = self::getData($sql);
var_dump($ret);
$count = (int) ($ret[0][""]);
return $count;
}
/*
* get the start pos for the matched $head->$start(eg. xml)
* start pos should behind the start a little,
* $end_pos: the pos of the end pattern
*/
function get_patten_string($data, $head, $end, $start_pos, &$end_pos) {
$p1 = strpos($data, $head, $start_pos);
if ($p1 === false) {
return false;
}
$p2 = $this->get_pattern_pos($data, $head, $end, $p1+1);
if ($p2 === false) {
return false;
}
$res = substr($data, $p1, $p2 - $p1);
$end_pos = $p2;
return $res;
}
function get_patten_string_right_pos($data, $head, $end, $start_pos, &$end_pos) {
$ret = $this->get_pattern_pos($data, $head, $end, $start_pos+1);
if ($ret === false) {
return false;
}
$end_pos = $ret;
$p1 = $start_pos; $p2 = $end_pos;
$res = substr($data, $p1, $p2 - $p1);
$end_pos = $p2;
return $res;
}
/*
* get the string for the matched $head->$start(eg. xml)
* NOTICE: the start pos is right the pos of the start pattern
* $end_pos: the pos of the end pattern
*/
function get_pattern_pos($data, $head, $end, $start_pos) {
/*
echo "get_pattern_pos\n";
var_dump($data);
var_dump($head);
var_dump($end);
var_dump($start_pos);
//*/
$p1 = strpos($data, $head, $start_pos);
$p2 = strpos($data, $end, $start_pos);
while ($p2 != false) {
if ($p1 == false || $p2 < $p1) {
return $p2;
}
$start_pos = $p2 + 1;
$p1 = strpos($data, $head, $start_pos);
$p2 = strpos($data, $end, $start_pos);
}
return false;
}
function get_start_and_end_pos(&$data, $field, $size, $start_pos, &$end_pos) {
echo "get_start_and_end_pos: ";
$id = $data[$start_pos][$field];
$end_pos = $start_pos;
for (; $end_pos < $size; $end_pos ++) {
if ( $data[$end_pos][$field] != $id ) {
break;
}
}
$end_pos --;
echo " {$id}, {$field}, {$start_pos}, {$end_pos}\n";
}
function getDateTime($date_s) {
$year_p = strpos($date_s, "年");
$mon_p = strpos($date_s, "月");
$day_p = strpos($date_s, "日");
$date = new DateTime();
if ($year_p == false || $mon_p == false || $day_p == false) {
$date->setDate(2000, 1, 1);
return $date->format('Y-m-d');
}
$year = (int) substr($date_s, 0, $year_p);
$month = (int) substr($date_s, $year_p + 1, $mon_p - $year_p - 1 );
$day = (int) substr($date_s, $mon_p+1, $day_p - $mon_p - 1);
$date->setDate($year, $month, $day);
return $date->format('Y-m-d');
}
/**
* used for batch query
* when insert_count == margin-1, do the sql and reset
* @param $sql
* @param $insert_count
* @param $margin
*/
function run_sql(&$sql, &$insert_count, $margin) {
if ( ($insert_count % $margin) >= ($margin - 1) ) {
echo "do sql\n";
var_dump($sql);
$ret = DB::runSql($sql);
$sql = "";
$insert_count = 0;
} else {
$insert_count++;
}
}
/*
* $mysql_id, order
*/
function syn_mssql_2_mysql($mysql_tbname, $mysql_fields, $mssql_tbname, $mssql_fields, $mysql_id_array = [], $mssql_id = null, $addtion_where = null, $pre_msdata_proc_function = null) {
// check variable
if ( !is_array($mysql_fields) || !is_array($mssql_fields) ) {
echo "input fields is not array";
return false;
}
if ( count($mssql_fields) != count($mysql_fields) ) {
echo "input fields is not equal";
return false;
}
// load partial every time
$sql = "";
if ($mssql_id !== null) {
// get total size
$sz = $this->get_ms_row_count($mssql_tbname, $addtion_where);
$start_pos = 0;
$margin = 100;
$end_pos = $start_pos + $margin;
echo "start pos: ";
var_dump($start_pos);
while ($start_pos < $sz) {
$sql = "SELECT * from (SELECT *, ROW_NUMBER() OVER (ORDER BY $mssql_id) as row FROM [dbo].[{$mssql_tbname}]) a WHERE a.row >= {$start_pos} and a.row <= {$end_pos}";
if ($addtion_where != null) {
$sql = "SELECT * from (SELECT *, ROW_NUMBER() OVER (ORDER BY $mssql_id) as row FROM [dbo].[{$mssql_tbname}] where {$addtion_where}) a WHERE a.row >= {$start_pos} and a.row <= {$end_pos}";
} else {
$sql = "SELECT * from (SELECT *, ROW_NUMBER() OVER (ORDER BY $mssql_id) as row FROM [dbo].[{$mssql_tbname}]) a WHERE a.row >= {$start_pos} and a.row <= {$end_pos}";
}
var_dump($sql);
$source_data = $this->getData($sql);
var_dump("source");
var_dump($source_data);
if ($pre_msdata_proc_function != null) {
//$pre_msdata_proc_function($source_data);
$source_data = call_user_func($pre_msdata_proc_function, $source_data);
}
$this->syn_data($source_data, $mssql_fields, $mysql_tbname, $mysql_fields, $mysql_id_array);
$start_pos = $end_pos + 1;
$end_pos = $start_pos + $margin;
}
foreach ($mssql_fields as $filed) {
$sql = $sql." `{$filed}`";
}
} else {
$sql = "SELECT ";
foreach ($mssql_fields as $filed) {
$sql = $sql." `{$filed}`";
}
$sql = $sql." from [dbo].[{$mssql_tbname}]";
if ($addtion_where != null) {
$sql = $sql." where {$addtion_where}";
}
$source_data = $this->getData($sql);
$this->syn_data($source_data, $mssql_fields, $mysql_tbname, $mysql_fields, $mysql_id_array);
}
}
function syn_data($source_data, $source_fields, $target_tbname, $target_fields, $target_key_array = []) {
echo "do syn_data\n";
$margin = 50;
$sz = count($source_data);
$count = $sz / $margin;
if ( $sz % $margin != 0 ) {
$count ++;
}
$slicde_data = array_chunk ($source_data, $count);
foreach ($slicde_data as $data_array) {
//var_dump($data_array);
$sql = "INSERT INTO {$target_tbname} (";
foreach ($target_fields as $fileds) {
$sql = $sql." `{$fileds}`,";
}
$tmp_sz = strlen($sql);
$sql = substr($sql, 0, $tmp_sz-1);
$sql = $sql.") VALUES";
foreach ($data_array as $item) {
//var_dump($item["fund_code"]);
$sql = $sql." (";
foreach($source_fields as $fields) {
if (!array_key_exists($fields, $item)) {
$item[$fields] = "";
}
$sql = $sql."'{$item[$fields]}', ";
}
// delete last ","
$tmp_sz = strlen($sql);
$sql = substr($sql, 0, $tmp_sz-2);
$sql = $sql."),";
}
// delete last ","
$tmp_sz = strlen($sql);
$sql = substr($sql, 0, $tmp_sz-1);
// add duplicate
$sql = $sql." ON DUPLICATE KEY UPDATE ";
foreach ($target_fields as $fields) {
if (in_array($fields, $target_key_array)) {
continue;
}
$sql = $sql." {$fields}=VALUES({$fields}),";
}
// delete last ","
$tmp_sz = strlen($sql);
$sql = substr($sql, 0, $tmp_sz-1);
var_dump($sql);
DB::runSql($sql);
}
}
/**
* 默认两张表的字段一致
* @param $source_table
* @param $target_table
* @param $order_id: whether add "''" in sql statement
* @param $is_value
* @param array $exclude_array: ignore fields
*/
function compareTable($source_table, $target_table, $order_id, $is_value, $exclude_array=[]) {
// get propertylist
echo "start compareTable";
$sql = "select `column_name` from `information_schema`.`columns` where `table_name`='{$source_table}'";
$ret = DB::getData($sql);
$filed_array = [];
foreach ($ret as $item) {
array_push($filed_array, $item["column_name"]);
}
// get id count for both
$max_target_id = $this->get_max_id($target_table, $order_id);
$max_source_id = $this->get_max_id($source_table, $order_id);
$max_id = max($max_target_id, $max_source_id);
$margin = 5000;
$start_id = 0;
$end_id = $margin + $start_id;
while ($start_id <= $max_id) {
echo " start_id: {$start_id}, end_id: {$end_id} \n";
$this->comparePartTable($source_table, $target_table, $order_id, $is_value, $filed_array, $exclude_array, $start_id, $end_id);
$start_id += $margin;
$end_id += $margin;
}
echo "end compareTable";
}
function comparePartTable($source_table, $target_table, $order_id, $is_value, $field_array, $exclude_array=[], $start_id, $end_id) {
if ($is_value) {
$sql_source = "select * from {$source_table} where $order_id >= {$start_id} and $order_id < {$end_id} order by $order_id";
$sql_target = "select * from {$target_table} where $order_id >= {$start_id} and $order_id < {$end_id} order by $order_id";
} else {
$sql_source = "select * from {$source_table} where $order_id >= '{$start_id}' and $order_id < '{$end_id}' order by $order_id";
$sql_target = "select * from {$target_table} where $order_id >= '{$start_id}' and $order_id < '{$end_id}' order by $order_id";
}
$source_data = DB::getData($sql_source);
$source_size = count($source_data);
$target_data = DB::getData($sql_target);
$target_size = count($target_data);
// doulbe loop to compare
$pos_source = 0;
$pos_target = 0;
for (; $pos_source < $source_size; ) {
for (; $pos_target < $target_size; ) {
$item_source = $source_data[$pos_source];
$item_target = $target_data[$pos_target];
if ($this->compareRow($item_source, $item_target, $field_array, $exclude_array)) {
$pos_source ++;
$pos_target ++;
continue;
} else {
$source_id = $item_source[$order_id];
$target_id = $item_target[$order_id];
if ($source_id == $target_id) {
// different
echo "different occur: \n";
echo " souce row: ";
var_dump($item_source);
echo " target row: ";
var_dump($item_target);
echo "\n";
$pos_source ++;
$pos_target ++;
break;
} else if ($source_id < $target_id) {
// target lack
// add data
echo "target lack: \n";
echo " source row: ";
var_dump($item_target);
echo "\n";
$pos_source ++;
break;
} else {
// source lack
echo "source lack: \n";
echo " target row: ";
var_dump($item_source);
echo "\n";
$pos_target ++;
}
}
}
if ($pos_target == $target_size) {
break;
}
}
for (; $pos_source < $source_size; $pos_source ++) {
$item_source = $source_data[$pos_source];
echo "target lack: \n";
echo " source row: ";
var_dump($item_source);
echo "\n";
}
for (; $pos_target < $target_size; $pos_target ++) {
$item_target = $target_data[$pos_target];
echo "source lack: \n";
echo " target row: ";
var_dump($item_target);
echo "\n";
}
}
function compareRow($source_row, $target_row, $filed_array, $exclude_array = []) {
foreach ( $filed_array as $filed ) {
if (in_array($filed, $exclude_array)) {
continue;
}
if ( $target_row[$filed] != $source_row[$filed] ) {
echo "compareRow: ";
echo "{$filed}";
echo " ";
echo $source_row[$filed];
echo " ";
echo $target_row[$filed];
echo "\n";
return false;
}
}
return true;
}
//分红,拆分信息读取
public static function splitprepare()
{
$data=array('bonus'=>array(),'split'=>array());
$dataBonus=&$data['bonus'];
$dataSplit=&$data['split'];
$bonus=DB::getData("SELECT code,date(date_divid) date_divid,per FROM `fund_bonus` ORDER BY `code`");
foreach ($bonus as $item)
{
$code=$item['code'];
if(!isset($dataBonus[$code]))
{
$dataBonus[$code]=array($item['date_divid']=>$item['per']);
}
else
{
$dataBonus[$code][$item['date_divid']]=$item['per'];
}
}
//下面计算拆分
$split=DB::getData("SELECT `code`,date(date_cal) date_cal,split_percent FROM `fund_split` ORDER BY `code`");
foreach ($split as $item)
{
$code=$item['code'];
if(!isset($dataSplit[$code]))
{
$dataSplit[$code]=array($item['date_cal']=>$item['split_percent']);
}
else
{
$dataSplit[$code][$item['date_cal']]=$item['split_percent'];
}
}
self::$data=$data;
self::log("get bonus and split ok");
}
/**
* 每日执行,消耗时间较长(2个小时)可中断,指定点继续执行
*/
function index($goto=0)
{
// self::log('Work will start at '.date('Y-m-d H:i',time()+3600*12))||sleep(3600*12);
$this->sync($goto);
$this->update_relative_bonus_split();
}
/**
* 每日执行
*/
function task2()
{
$this->funddividend(); //分红同步
$this->resolution(); //拆分同步
app::run(array('bond','index')); //中证全债数据抓取
}
/**
* 资产配置,有关季度的数据,每月执行,消耗内存较大,执行时间长(2个小时)
*/
function task3()
{
$this->stock();
}
/*************************************基金净值同步 需每日同步***********************************/
function sync($goto=0,$countRange=false)
{
$sql="SELECT DISTINCT SYMBOL FROM [dbo].[FUND_NAV] WHERE NAV IS NOT NULL AND ACCUMULATIVENAV IS NOT NULL ORDER BY SYMBOL";
$data=self::getData($sql);
$symbols=array_column($data,'SYMBOL');
$all=count($symbols);
self::log('total symbols :'.$all);
foreach ($symbols as $num=>$symbol)
{
// 240021 260102 690212是一个货币基金
if($num<$goto or in_array($symbol,array('000366','240021','260102','690212'))) //排除部分基金
{
continue;
}
$msg=$this->syncSingle($symbol,$countRange);
self::log(($num+1).' Done,Remain '.($all-1-$num).'=>'.$msg,true);
}
}
/**
* 启动range涨幅纠偏工作,可修复近期range的错误数据,耗时较长
*/
function startCount($goto=0)
{
$this->sync($goto,true);
}
/**
* 同步单个基金,无条件同步
*/
public function syncSingle($symbol,$countRange=false)
{
if($countRange)
{
return $this->countRange($symbol);
}
$sql="SELECT NAV,ACCUMULATIVENAV,CONVERT(DATE,TRADINGDATE) TRADINGDATE,TRADINGDATE TRADINGDATE_FULL, UPDATETIME FROM (SELECT TOP 10 * FROM [dbo].[FUND_NAV] WHERE SYMBOL={$symbol} ORDER BY TRADINGDATE DESC) a ORDER BY a.TRADINGDATE ASC";
$origin=self::getData($sql);
$sql="INSERT INTO `fund_value` (`code`,`unit`,`all`,`range`,`create_date`,`update_date`) VALUES ('{$symbol}',:unit,:all,:range,:create_date,:update_date) ON DUPLICATE KEY UPDATE update_date=:update_date,`range`=:range,`unit`=:unit,`all`=:all";
$stm=DB::prepare($sql);
$map=array_column($origin,null,'TRADINGDATE');
$keys=array_keys($map);
$i=0;
foreach ($origin as $index=>$item)
{
if($index<1)continue;
$date=$item['TRADINGDATE'];
//计算涨幅 $range
$range=self::getRange($date,$map,$keys,$symbol);
$stm->bindParam(':unit',$item['NAV']);
$stm->bindParam(':all',$item['ACCUMULATIVENAV']);
$stm->bindParam(':range',$range);
$stm->bindParam(':create_date',$item['TRADINGDATE_FULL']);
$stm->bindParam(':update_date',$item['UPDATETIME']);
var_dump($stm);
$ret=$stm->execute();
$i++;
self::log("range for {$symbol} of date {$date} is {$range} => {$ret}");
}
return "{$symbol} UPDATEED {$i} ,NEW {$item['TRADINGDATE']}";
}
/**
* 由历史数据计算涨幅
*/
private static function getRange($date,$map,$keys,$symbol)
{
$keyIndex=array_search($date,$keys);
$item=$map[$date];
$prevDate=$keyIndex>0?$keys[$keyIndex-1]:null;//上一个交易日
$prevItem=is_null($prevDate)?0:$map[$prevDate];
$prevNav=$prevItem?floatval($prevItem['NAV']):0;
$currentNav=floatval($item['NAV']);
//需要检测是否含有分红等
$currentNav=self::fixCurrentNav($currentNav,$symbol,$date);
if($prevNav)
{
$percent=sprintf('%.2f',round(($currentNav-$prevNav)/$prevNav,4)*100)."%";
}
else
{
$percent='0.00%';
}
return $percent;
}
//修正range,遍历全部
private function countRange($symbol)
{
// $sql="SELECT unit,`all`,`range`,date(create_date) create_date FROM (SELECT * FROM `fund_value` WHERE `code`={$symbol} ORDER BY create_date DESC LIMIT 60) a ORDER BY a.create_date ASC";
$sql="SELECT unit,`all`,`range`,date(create_date) create_date FROM `fund_value` WHERE `code`={$symbol} ORDER BY create_date ";
$data=DB::getData($sql);
$i=$j=0;
foreach ($data as $i=>$item)
{
if($i==0)
{
$prevNav=$item['unit'];
continue;
}
$oldRange=$item['range'];
$date=$item['create_date'];
$currentNav=$item['unit'];
//需要检测是否含有分红等
$currentNav=self::fixCurrentNav($currentNav,$symbol,$date);
if(!$prevNav)
{
var_dump($symbol,$date,$prevNav);die;
}
$range=sprintf('%.2f',round(($currentNav-$prevNav)/$prevNav,4)*100)."%";
$prevNav=$item['unit'];
if($range==$oldRange)
{
$i++;
// self::log("{$symbol} Range for {$date} id OK {$range}");
}
else
{
$j++;
$sql="UPDATE `fund_value` SET `range`='{$range}' WHERE code='{$symbol}' AND date(create_date)='{$date}' ";
$ret=DB::runSql($sql);
self::log("{$symbol} Update Range for {$date}, Fixed {$oldRange}=>{$range} , {$ret}");
}
}
return "OK {$i},Fixed {$j}";
}
private static function fixCurrentNav($currentNav,$code,$date)
{
if(!self::$data)
{
self::splitprepare();
}
if(isset(self::$data['bonus'][$code][$date]))
{
$currentNav=$currentNav+self::$data['bonus'][$code][$date];
}
else if(isset(self::$data['split'][$code][$date]))
{
$currentNav=$currentNav*self::$data['split'][$code][$date];
}
return $currentNav;
}
/************stock同步,无需每日,执行大约3小时,首次消耗内存较小,再次执行消耗很大(700Mb)*********/
public function stock($code=null)
{
if(DIRECTORY_SEPARATOR=='/')
{
exit("You Should not run this on linux system");//linux 系统下,mb_convert_encoding转换出现乱码,需在windows电脑执行此操作
}
ini_set('memory_limit', '800M');
$sql="SELECT DISTINCT MASTERFUNDCODE FROM [dbo].[FUND_PORTFOLIO_STOCK] ORDER BY MASTERFUNDCODE";
if($code)
{
$sql="SELECT DISTINCT MASTERFUNDCODE FROM [dbo].[FUND_PORTFOLIO_STOCK] WHERE MASTERFUNDCODE='{$code}'";
}
$data=self::getData($sql);
$sql="SELECT `updateid` FROM `fund_stock`";
$ret=DB::getData($sql);
$ids=array_column($ret,'updateid');
unset($ret,$sql);
self::log('total num '.count($data));
foreach($data as $item)
{
$code=$item['MASTERFUNDCODE'];
$sql="SELECT * FROM [dbo].[FUND_PORTFOLIO_STOCK] WHERE MASTERFUNDCODE='{$code}' ORDER BY STARTDATE";
$funData=self::getData($sql);
$this->stockToMysql($code,$funData,$ids);
}
self::log('finished');
}
private function stockToMysql($code,$data,$ids)
{
$sql="INSERT INTO `fund_stock` (`fund_code`,`code`,`name`,`percent`,`mount`,`price`,`update_date`,`start_date`,`end_date`,`updateid`) VALUES ('{$code}',:code,:name,:percent,:mount,:price,:update_date,:start_date,:end_date,:updateid) ";
$sql2="UPDATE `fund_stock` SET `name`=:name WHERE `updateid`=:updateid ";
try
{
$stm=DB::prepare($sql);
$stm2=DB::prepare($sql2);
foreach ($data as $item)
{
if(!in_array($item['UPDATEID'],$ids))
{
$name=mb_convert_encoding($item['STOCKNAME'],"UTF-8","GBK");
// iconv("GBK", "UTF-8", $item['STOCKNAME']);
$stm->bindParam(':code',$item['SYMBOL']);
$stm->bindParam(':name',$name);
$stm->bindParam(':percent',$item['PROPORTION']);
$stm->bindParam(':mount',$item['SHARES']);
$stm->bindParam(':price',$item['MARKETVALUE']);
$stm->bindParam(':update_date',$item['UPDATETIME']);
$stm->bindParam(':start_date',$item['STARTDATE']);
$stm->bindParam(':end_date',$item['ENDDATE']);
$stm->bindParam(':updateid',$item['UPDATEID']);
$stm->execute();
self::log("add {$item['UPDATEID']} for {$code}");
}
else
{
$name=mb_convert_encoding($item['STOCKNAME'],"UTF-8","GBK");
$stm2->bindParam(':name',$name);
$stm2->bindParam(':updateid',$item['UPDATEID']);
$stm2->execute();
self::log("CODE {$code} UPDATEID {$item['UPDATEID']} UPDATE");
}
}
}
catch(PDOException $e)
{
exit($e->getMessage());
}
}
/*********分红同步 FUND_FUNDDIVIDEND 增量同步,不修改历史数据*************/
function funddividend()
{
//数据大约6000条,一次取出
$sql="SELECT SYMBOL,RECORDDATE,PRIMARYEXDIVIDENDDATE,DISTRIBUTIONPLAN,PRIMARYPAYDATE_DIVIDEND,UPDATETIME,DIVIDENDPERSHARE,UPDATEID FROM [dbo].[FUND_FUNDDIVIDEND] ORDER BY SYMBOL";
$data=self::getData($sql);
$sql="SELECT updateid FROM `fund_bonus`";
$ret=DB::getData($sql);
$ids=array_column($ret,'updateid');
unset($ret);
$sql="INSERT INTO `fund_bonus` (`code`,`year`,`date_reg`,`date_divid`,`bonus`,`date_grant`,`update_date`,`per`,`updateid`) VALUES (:code,:year,:date_reg,:date_divid,:bonus,:date_grant,:update_date,:per,:updateid) ON DUPLICATE KEY UPDATE date_reg=VALUES(date_reg), date_divid=VALUES(date_divid), bonus=VALUES(bonus), date_grant=VALUES(date_grant), update_date=VALUES(update_date), per=VALUES(per)";
$stm=DB::prepare($sql);
$stm=DB::prepare($sql);
$add=$ignore=0;
foreach ($data as $item)
{
if(!in_array($item['UPDATEID'],$ids))
{
if(!empty($item['PRIMARYEXDIVIDENDDATE']) && !empty($item['PRIMARYPAYDATE_DIVIDEND']))
{
$year=substr($item['RECORDDATE'],0,4);
//$bonus=iconv("GBK", "UTF-8", $item['DISTRIBUTIONPLAN']);
$bonus=$item['DISTRIBUTIONPLAN'];
$stm->bindParam(':code',$item['SYMBOL']);
$stm->bindParam(':year',$year);
$stm->bindParam(':date_reg',$item['RECORDDATE']);
$stm->bindParam(':date_divid',$item['PRIMARYEXDIVIDENDDATE']);
$stm->bindParam(':bonus',$bonus);
$stm->bindParam(':date_grant',$item['PRIMARYPAYDATE_DIVIDEND']);
$stm->bindParam(':update_date',$item['UPDATETIME']);
$stm->bindParam(':updateid',$item['UPDATEID']);
$stm->bindParam(':per',$item['DIVIDENDPERSHARE']);
self::log('add data for '.$item['SYMBOL']);
$stm->execute();
$add++;
}
else
{
self::log('ignore empty data '.$item['SYMBOL']);
$ignore++;
}
}
}
self::log("finished add {$add} ignore {$ignore}");
}
/*************************************拆分同步***********************************/
function resolution()
{
$sql="SELECT SYMBOL,SPLITRECORDDATE,SPLITDOBJECT,SPLITRATIO,UPDATETIME,UPDATEID FROM [dbo].[FUND_RESOLUTION] ORDER BY SYMBOL";
$data=self::getData($sql);
$sql="SELECT updateid FROM `fund_split`";
$ret=DB::getData($sql);
$ids=array_column($ret,'updateid');
unset($ret);
$sql="INSERT INTO `fund_split` (`code`,`year`,`date_cal`,`split_type`,`split_percent`,`update_date`,`updateid`) VALUES (:code,:year,:date_cal,:split_type,:split_percent,:update_date,:updateid)";
$stm=DB::prepare($sql);
$add=$ignore=0;
foreach ($data as $item)
{
if(!in_array($item['UPDATEID'],$ids))
{
if(!empty($item['SPLITRECORDDATE']) && !empty($item['SPLITRATIO']))
{
$year=substr($item['SPLITRECORDDATE'],0,4);
$split_type=mb_convert_encoding($item['SPLITDOBJECT'],"UTF-8","GBK");
$stm->bindParam(':code',$item['SYMBOL']);
$stm->bindParam(':year',$year);
$stm->bindParam(':date_cal',$item['SPLITRECORDDATE']);
$stm->bindParam(':split_type',$split_type);
$stm->bindParam(':split_percent',$item['SPLITRATIO']);
$stm->bindParam(':update_date',$item['UPDATETIME']);
$stm->bindParam(':updateid',$item['UPDATEID']);
$add++;
$stm->execute();
self::log("add data for {$item['SYMBOL']}");
}
else
{
$ignore++;
self::log('ignore empty data '.$item['SYMBOL']);
}
}
}
self::log("finished add {$add} ignore {$ignore}");
}
/**
* 检查程序,检查阶段涨幅数据是否更新
*/
function check()
{
$code=530008;
$sql="SELECT * FROM `fund_data` WHERE `code`={$code} ORDER BY create_date DESC";
$data=DB::getLine($sql);
$lastUpdate=strtotime($data['update_date']);
$last=date('Y-m-d H:i:s',time()-21600);
if($lastUpdate<(time()-21600))
{
self::log('!!!!Warning:fund_data was not update at least 6 hours');
}
else
{
$num=DB::getVar("SELECT count(1) FROM `fund_data` where update_date > '{$last}'");
self::log("fund_data was updated at {$data['update_date']},please check {$code} {$data['increase']}");
self::log("total update {$num}/3034");
}
//下面检查货币基金
$date=DB::getVar("SELECT date(create_date) create_date FROM `fund_value` WHERE `code`=740601 ORDER BY create_date DESC LIMIT 1");
if($date!=date('Y-m-d',strtotime('-1 days')))
{
self::log("!!!!Warning:fund_value has no yesterday data,recent date {$date}");
}
else
{
self::log("fund_value last update {$date}");
$last=date('Y-m-d 00:00:00',strtotime('-1 days'));
$num=DB::getVar("SELECT count(1) FROM `fund_value` where create_date = '{$last}'");
self::log("total update {$num}/3107");
}
}
//从描述中算出每份派发现金,存储到per,无副作用,无需每天执行
public function bonusfix()
{
$i=$j=0;
$data=DB::getData("SELECT * FROM `fund_bonus`");
foreach ($data as $item)
{
$id=$item['id'];
$bonus=$item['bonus'];
$oldPer=$item['per'];
if(preg_match_all('/.*?10.*?([\d\.]+)/',$bonus,$matches))
{
$tmp=$matches[1][0];
$per=round(($tmp/10),4);
if($per==0)
{
exit("Zero Found {$per} {$id}");
}
if($oldPer!=$per)
{
$i++;
DB::runSql("UPDATE `fund_bonus` SET `per`='{$per}' WHERE id={$id}");
self::log("{$id} FIXED {$oldPer}=>{$per}");
}
else
{
$j++;
self::log("{$id} IS ALREADY NEW");
}
}
else
{
exit("not Match {$id}");
}
}
$num=count($data);
self::log("FIXED {$i}, OK {$j} ,Total {$num}");
}
/**
* 资产配置,基金涨幅,每天抓取,所有基金
*/
public function assets($code=530008)
{
$url="http://www.howbuy.com/fund/{$code}/";
$html=file_get_contents($url);
$pattern='/class="nTab9 jjzf_content" id="nTab9_0" style="display: block;">([\s\S]*?)sfw_tips_c/';
$data=array('increase'=>'','increase_avg'=>'','increase_300'=>'','asset'=>'','trade'=>'');
if(preg_match_all($pattern, $html, $matches))
{
$text=$matches[0][0];
if(preg_match_all('/区间回报<\/td>([\s\S]*?)<\/tr>/',$text,$matches2))
{
$tmp=explode(PHP_EOL,$matches2[1][0]);
$str=array();