first commit

This commit is contained in:
yangshuimiao
2023-10-16 12:58:41 +08:00
commit 3a09f3ca67
1512 changed files with 570984 additions and 0 deletions
+185
View File
@@ -0,0 +1,185 @@
<?php
ini_set("display_errors","1");
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
//ajax: get stock list for select
if($_REQUEST['t']=='stockList'){
if($_REQUEST['t_vendor']=='方正证券'){
$sql= <<< EOF
select distinct(ts_code) ts_code,ts_name from trade_record
where tprice>0 and (ts_code not like '7%' and ts_code not like '1%') and length(trade_id)=5 order by ts_code
EOF;
}elseif($_REQUEST['t_vendor']=='长江证券'){
//length(0+ts_name)!=length(ts_name) 判断ts_name 不能为纯数字
$sql= <<< EOF
select distinct(ts_code) ts_code,ts_name from trade_record_cj
where tprice>0 and ts_code not like '7%' and length(0+ts_name)!=length(ts_name) order by ts_code
EOF;
}
$result = $mysqli->query($sql);
$data = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode(array(
"status" => "1",
'stocks'=> $data,
"company"=>$_REQUEST['t_vendor'],
));
}
/**
* AJAX get finance Data from getFianceData class
*/
if($_REQUEST['t']=='financeData'){
include_once __DIR__."/getFinanceData.class.php";
include_once __DIR__."/getBasic.inc.php";
$years=yearList($_REQUEST['yst'],$_REQUEST['yed']);
$fina = new getFinance();
$fina->ts_code=$_REQUEST['ts_code'];
$dataAll=array();
foreach($years as $year){
$fina->finDate=$year;
$dataAll[] =$fina->getFinanceData();
}
for($i=0;$i<count($dataAll);$i++){
$n=0;
foreach ($dataAll[$i] as $key=>$val){
$n++;
if(strlen($n)<2) $n='0'.$n;
if($key=='ts_code') {
$key=$n.'.股票代码';
$val=tscodeToName($val);
$n--;
continue; //不显示股票代码
}elseif($key=='period') {
$key=$n.'.报告期';
$val=yearToname($val);
$n--;
continue; //不显示报告期
}else $key=$n.'.'.$key;
if($i==0) $data[$n][]=$key; //首列加
$data[$n][]=$val;
}
}
//strip key from array $data
//dataTable must NOT have any key of json
$data=array_values($data);
echo json_encode(array("data"=>$data));
}
/*
*esfTBD: 二手房Trade By Day
*/
if($_REQUEST['t']=='esfTBD'){
$dataTrade=esfTradeDaily();
$dataList=esfListDaily();
echo json_encode(array(
"status" => "1",
'dataTrade'=> $dataTrade,
'dataList'=>$dataList
));
}
/*
*esfListDaily: 二手房每日挂牌数量
*/
if($_REQUEST['t']=='esfListDaily'){
$data=esfListDaily();
echo json_encode(array(
"status" => "1",
'datas'=> $data
));
}
function esfTradeDaily(){
global $mysqli;
$sql= <<<EOF
SELECT
distinct(ej.uuid) uid ,
date_format(tdate,'%Y-%m-%d') td,
eje.val district,
eje1.val qty,
eje2.val area
FROM
`estate_json` ej
left join estate_json_ext eje on ej.uuid=eje.uuid and eje.val='{$_REQUEST['district']}'
left join estate_json_ext eje1 on eje1.id=eje.id+3
left join estate_json_ext eje2 on eje2.id=eje.id+4
where ej.data_type='5' and (ej.tdate>='{$_REQUEST['t_start']}' and ej.tdate<='{$_REQUEST['t_end']}')
EOF;
$result = $mysqli->query($sql);
$data = $result->fetch_all(MYSQLI_ASSOC);
return $data;
}
function esfListDaily(){
global $mysqli;
$sql= <<<EOF
SELECT
distinct(ej.uuid) uid ,
date_format(tdate,'%Y-%m-%d') td,
eje.val district,
eje1.val qty,
eje2.val price
FROM
`estate_json` ej
left join estate_json_ext eje on ej.uuid=eje.uuid and eje.val='{$_REQUEST['district']}'
left join estate_json_ext eje1 on eje1.id=eje.id+3
left join estate_json_ext eje2 on eje2.id=eje.id+5
where ej.data_type='8' and (ej.tdate>='{$_REQUEST['t_start']}' and ej.tdate<='{$_REQUEST['t_end']}')
EOF;
$result = $mysqli->query($sql);
$data = $result->fetch_all(MYSQLI_ASSOC);
return $data;
}
/*
*newTBD: 新房Trade By Day
*/
if($_REQUEST['t']=='newTBD'){
$sql= <<<EOF
SELECT
distinct(ej.uuid) uid ,
date_format(tdate,'%Y-%m-%d') td,
eje.val district,
eje1.val qty,
eje2.val area
FROM
`estate_json` ej
left join estate_json_ext eje on ej.uuid=eje.uuid and eje.val='{$_REQUEST['district']}'
left join estate_json_ext eje1 on eje1.id=eje.id+3
left join estate_json_ext eje2 on eje2.id=eje.id+4
where ej.data_type='1' and (ej.tdate>='{$_REQUEST['t_start']}' and ej.tdate<='{$_REQUEST['t_end']}')
EOF;
$result = $mysqli->query($sql);
$data = $result->fetch_all(MYSQLI_ASSOC);
$sql= <<<EOF
SELECT
distinct(ej.uuid) uid ,
date_format(tdate,'%Y-%m-%d') td,
eje.val district,
eje1.val area,
eje2.val qty
FROM
`estate_json` ej
left join estate_json_ext eje on ej.uuid=eje.uuid and eje.val='{$_REQUEST['district']}'
left join estate_json_ext eje1 on eje1.id=eje.id+3
left join estate_json_ext eje2 on eje2.id=eje.id+4
where ej.data_type='4' and (ej.tdate>='{$_REQUEST['t_start']}' and ej.tdate<='{$_REQUEST['t_end']}')
EOF;
$result = $mysqli->query($sql);
$data2 = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode(array(
"status" => "1",
'datas'=> $data,
'dataExt'=> $data2
));
}
+150
View File
@@ -0,0 +1,150 @@
<?php
require_once "vendor/autoload.php";
use PhpOffice\PhpSpreadsheet\Reader\Csv;
/**
* Read an excel file and return an array of excel cell data.
* @param $file: excel file to read.
* @return array
*/
function readMyExcel($file): array
{
//$inputFileName = dirname(__FILE__) . '/xls/fz20180501-20190101.xls';
//$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
$reader = new Csv();
$reader->setInputEncoding("CP936");
//$reader->setCodepage("CP936");
$excel = $reader->load($file);
return $excel->getActiveSheet()->toArray(null,true,true,false);
}
/**
* Upload excel data to mysql table trade_record
* @param $data: array which get from excel file.
* @param $company: 证券公司名
* @return array: msg
*/
function dbOp($data,$company)
{
$mysqli = new mysqli('localhost', 'root', 'nancysimon', 'myquant');
$maxrow = count($data);
$maxcol = count($data[0]);
$msg = array();
for ($row = 0; $row < $maxrow; $row++) {
if ($row == 0) {
//检查文件与证券公司是否匹配
if(($data[$row][4]=='买卖标志' and $company=='方正证券') or ($data[$row][4]=='操作' and $company=='长江证券'))
continue; //skip 1st row;
else{
echo json_encode(array(
"status" => "-1",
"row1"=> $data[$row],
'company'=> $company,
"msg" => "文件格式不正确或与证券公司不匹配,请重试!",
));
return false;
}
}
//处理时间字段, 方正证券格式: hhmmss需要特别处理, 长江证券时间格式正常: hh:mm:ss
$tm = $data[$row][1]; //format $time
if ($tm == 0) $data[$row][1] = '00:00:00';
elseif($company=='方正证券') $data[$row][1] = substr($tm, 0, -4) . ':' . substr($tm, -4, 2) . ':' . substr($tm, -2);
//处理长江证券的改动:去掉item 9,15,重置键名
if($company=='长江证券'){
unset($data[$row][9]);
unset($data[$row][15]);
$data[$row]=array_values($data[$row]);
$maxcol = count($data[$row]); //重置 maxcol
}
/**
* addslashes处理
* 方正证券14 其他费用,15:备注(需要处理)
* 长江证券14备注(需要处理),15:交易市场
*/
$data[$row][14] = addslashes($data[$row][14]); // add slash avoid sql clash
$data[$row][15] = addslashes($data[$row][15]); // add slash avoid sql clash
// duplicate check for each row
if (recordDupCheck($data[$row], $mysqli,$company)) {
$msg[] = addslashes("Row <span style='color:#ff0000'> $row </span> exist. Skip!<br />");
continue;
}
//else var_dump($data[$row]);
$values = ''; //initial $values;
for ($col = 0; $col < $maxcol; $col++) {
$values .= "'" . $data[$row][$col] . "',";
}
$values = rtrim($values, ','); //如果需要,此行去除末尾逗号(,)
if($company=='方正证券') {
$sql = <<<EOF
insert into
trade_record(
`tdate`,`ttime`, `ts_code`, `ts_name`, `flg`, `tprice`, `tvol`,
`trade_id`, `entrust_id`, `holder_code`, `tamount`, `commission`,
`tax1`, `tax2`, `tax3`, `note`, `t_vendor`)
values(
$values,
'$company'
)
EOF;
}elseif($company=='长江证券'){
$sql = <<< EOF
insert into
trade_record_cj(
`tdate`, `ttime`, `ts_code`, `ts_name`, `flg`, `tvol`, `tprice`,
`tamount`, `entrust_id`, `trade_id`, `tax1`, `tax2`, `tax3`,
`ttl_amount`, `note`, `trade_mkt`, `uaccount`, `t_vendor`)
values(
$values,
'$company'
)
EOF;
}
$mysqli->query($sql) or die("Data upload failure: " . $sql);
unset($values); //release $values;
$msg[] = addslashes("Row <span style='color:#ff0000'> $row </span> uploaded.<br />");
}
$msg[] = addslashes("All data uploaded!<p />");
$mysqli->close();
return $msg;
}
/**
* Duplicate check of each row by given $row
* @param $row: data of 1 row
* @param $mysqli: mysqli handle
* @return bool return true if record exist
*/
function recordDupCheck($row,$mysqli,$company): bool
{
if($company=='方正证券') {
$sql = <<< EOF
select *
from trade_record
where
tdate = '$row[0]'
and ttime = '$row[1]'
and ts_code = '$row[2]'
and note = '$row[15]'
EOF;
}elseif($company=='长江证券') {
$sql = <<< EOF
select *
from trade_record_cj
where
tdate = '$row[0]'
and ttime = '$row[1]'
and ts_code = '$row[2]'
and note = '$row[14]'
EOF;
}
$result=$mysqli->query($sql) or die($sql."<br />\n");
$r = $result->num_rows;
$result->free();
if($r > 0) return true;
else return false;
}
Binary file not shown.
+314
View File
@@ -0,0 +1,314 @@
<?php
/**
* 获取PE_TTM,PB,PS等历史数据
* @param $ts_code ts code
* @param $day_st start date
* @param $day_end end date
* @param $item: PE_TTM, PB,PS
* @return array
*/
function getBasicData($ts_code,$day_st,$day_end,$item){
$day_st=date('Ymd',strtotime($day_st));
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
$where = " and trade_date>'".$day_st."'";
if($day_end) {
$day_end=date('Ymd',strtotime($day_end));
$where .= " and trade_date <'".$day_end."'";
}
$sql= <<<EOF
select trade_date, $item as pe_ttm from stock_his_basic_pro where ts_code = '$ts_code' $where order by trade_date asc
EOF;
#echo $sql;
$result = $mysqli->query($sql);
$tDate=$idx=$data=$data_clean=array(); # $data_clean is an array without null
if($result && $result->num_rows>0) {
#$data = $result->fetch_all();
while($row=$result->fetch_assoc()){
$trade_date=substr($row['trade_date'],0,4).'-'.substr($row['trade_date'],4,2).'-'.substr($row['trade_date'],6,2);
#$trade_date1=strtotime($row['trade_date']);
array_push($tDate,$trade_date);
array_push($idx,$row['pe_ttm']);
$data_tmp = array("value"=>array($trade_date,$row['pe_ttm']));
array_push($data,$data_tmp);
if($data_tmp['value'][1]>0) array_push($data_clean,$data_tmp['value'][1]);
}
}
$data_last= round($data_clean[count($data_clean)-1],2);
$data_max= round(max($data_clean),2);
$data_min= round(min($data_clean),2);
if(count($data_clean)>0) $data_avg= round(array_sum($data_clean)/count($data_clean),2);
else $data_avg=null;
#Free result and close connection.
$result->free();
$mysqli->close();
return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}
function ts_code_conv($ts_code){
$tmp = explode('.',$ts_code);
switch($tmp[1]){
case 'SZ':
return $ts_code;
case 'SH':
return $ts_code;
case 'sz':
return strtoupper($ts_code);
case 'sh':
return strtoupper($ts_code);
default:
if(substr($tmp[0],0,2)=='60') return $tmp[0].'.SH';
elseif(substr($tmp[0],0,2)=='30') return $tmp[0].'.SZ';
elseif(substr($tmp[0],0,2)=='00') return $tmp[0].'.SZ';
else return $ts_code;
}
}
function getStockHist($ts_code,$day_st,$day_end){
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
$where = " and trade_date>='".$day_st."'";
if($day_end) $where .= " and trade_date <='".$day_end."'";
$sql= <<<EOF
select trade_date, close from stock_his_pro where ts_code = '$ts_code' $where order by trade_date asc
EOF;
//echo $sql;
$result = $mysqli->query($sql);
$tDate=$idx=$data=array();
if($result && $result->num_rows>0) {
#$data = $result->fetch_all();
while($row = $result->fetch_assoc()){
//$trade_date=substr($row['trade_date'],0,4).'-'.substr($row['trade_date'],4,2).'-'.substr($row['trade_date'],6,2);
//$trade_date1=strtotime($row['trade_date']);
array_push($tDate,$row['trade_date']);
array_push($idx,$row['close']);
array_push($data,array("value"=>array($row['trade_date'],$row['close'])));
}
}
#Free result and close connection.
$result->free();
$mysqli->close();
return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data);
}
function tscodeToName($ts_code){
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
$sql= "select name from stock_all_pro where ts_code='{$ts_code}'";
$result = $mysqli->query($sql);
if($result && $result->num_rows >0) $row = $result->fetch_assoc();
$result->free();
$mysqli->close();
return $row['name'];
}
function getBasicExtData($ts_code,$item,$day_st,$day_end){
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
$where = " and trade_date>'".$day_st."' ";
if($item=='total_mv_all' or $item=='circ_mv_all') {
$where .= "and vol/10000/10000 > 1";
$ts_code='all';
$item=substr($item,0,-4);
}
if($day_end) $where .= " and trade_date <'".$day_end."'";
$sql= <<<EOF
select * from stock_basic_ext where code = '$ts_code' and item='$item' $where order by trade_date asc
EOF;
//echo $sql;
$result = $mysqli->query($sql);
$tDate=$idx=$data=array();
if($result && $result->num_rows>0) {
#$data = $result->fetch_all();
while($row=$result->fetch_assoc()){
if($item=='total_mv' or $item=='circ_mv') {
$row['vol']=$row['vol']/10000/10000; #单位:亿
}
$trade_date=substr($row['trade_date'],0,4).'-'.substr($row['trade_date'],4,2).'-'.substr($row['trade_date'],6,2);
#$trade_date=substr($row['trade_date'],0,4).'-'.substr($row['trade_date'],4,2).'-'.substr($row['trade_date'],6,2);
$trade_date=substr($row['trade_date'],0,10);
array_push($tDate,$trade_date);
array_push($idx,$row['vol']);
array_push($data,array("value"=>array($trade_date,round($row['vol'],2))));
}
}
#Free result and close connection.
$result->free();
$mysqli->close();
$data_last= round($idx[count($idx)-1],2);
$data_max= round(max($idx),2);
$data_min= round(min($idx),2);
if(count($idx)>0) $data_avg= round(array_sum($idx)/count($idx),2);
return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}
/*
f2: date
f9: share num
f10: share money
f11: share ratio 流动比例
f12: share ratio 总股本比例
*/
/*
function temporary disabled.
TODO: delete if useless confirm.
function getStockIhHist($ts_code,$day_st,$day_end,$item){
$ts_code = ts_code_conv($ts_code);
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
$where = " and f2>'".$day_st."'";
if($day_end) $where .= " and f2<'".$day_end."'"; // F2: date
$sql = <<<EOF
select f2, sum(f9) f9,round(sum(f10),2) sumf10,round(sum(f11),2) sumf11 from ih_by_ts_code
where f0 = '$ts_code' $where group by f2 order by f2 asc
EOF;
//EOF必须在行首,且后面不能有空格
$result = $mysqli->query($sql);
$tDate=$idx=$data=array();
if($result && $result->num_rows>0) {
#$data = $result->fetch_all();
while($row=$result->fetch_assoc()){
array_push($tDate,$row['f2']);
array_push($idx,$row['vol']); //$item can choose f9,f10,f11,f12
array_push($data,array("value"=>array($trade_date,$row['vol'])));
}
}
#Free result and close connection.
$result->free();
$mysqli->close();
return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data);
}
*/
/**
* @param $date : given a date (yyyy-mm-dd)
* @param $gap : days +/- n(int)
* @return false|string
*/
function dateGap($date,$gap){
$str="$date $gap day";
return date('Y-m-d',strtotime($str));//日期天数相加函数
}
/**
* @param string $email: default null
* @return bool true
*/
function tradeStocksList($email=null){
global $mysqli;
if($_REQUEST['t_vendor']=='方正证券'){
$sql= <<< EOF
select distinct(ts_code) ts_code,ts_name from trade_record
where tprice>0 and (ts_code not like '7%' and ts_code not like '1%') and length(trade_id)=5 order by ts_code
EOF;
}elseif($_REQUEST['t_vendor']=='长江证券'){
//length(0+ts_name)!=length(ts_name) 判断ts_name 不能为纯数字
$sql= <<< EOF
select distinct(ts_code) ts_code,ts_name from trade_record_cj
where tprice>0 and ts_code not like '7%' and length(0+ts_name)!=length(ts_name) order by ts_code
EOF;
}
$result = $mysqli->query($sql);
$data = $result->fetch_all(MYSQLI_ASSOC);
$option='';
foreach ( $data as $item){
$option .= "<option label='{$item['ts_name']}' value='{$item['ts_code']}'></option>\n";
}
$html = <<< EOF
<input id="ts_code" name= "ts_code" list="codeList" autocomplete="off"/>
<datalist id="codeList">
$option
</datalist>
<script>
$("#ts_code").val('{$_REQUEST['ts_code']}');
</script>
EOF;
echo $html;
return true;
}
function vendorList($id='t_vendor'){
$html = <<<EOF
<select id="{$id}" name= "{$id}" autocomplete="off" >
<option value="方正证券">方正证券</option>
<option value="长江证券">长江证券</option>
</select>
<script>
$("#{$id}").val('{$_REQUEST[$id]}');
</script>
EOF;
echo $html;
return true;
}
/**
* 根据年份区间,获取财报日期清单
* @param $yst
* @param $yed
*/
function yearList($yst,$yed){
$n = $yed-$yst+1;
$thisYear=date('Y'); //yyyy,eg.2022
$thisMonDay=date('md'); //mmdd,eg.0331
$years=array();
for($i=0;$i<$n;$i++){
if(($yst+$i)<($thisYear-1) ) $years[]=($yst+$i)."1231"; //前年及以前
//去年
if(($yst+$i)==($thisYear-1)and $thisMonDay<='0430') $years[]=($yst+$i)."0930";
if(($yst+$i)==($thisYear-1)and $thisMonDay >'0430') $years[]=($yst+$i)."1231";
//今年
if(($yst+$i)==$thisYear){
switch ($thisMonDay){
case $thisMonDay<='0430':
//一季报未公布do nothing
break;
case $thisMonDay>'0430' && $thisMonDay<= '0831':
//公布一季报
$years[]=($yst+$i)."0331";
break;
case $thisMonDay>'0831' && $thisMonDay<= '1031':
//公布一季报
$years[]=($yst+$i)."0630";
break;
case $thisMonDay>'1031':
//公布一季报
$years[]=($yst+$i)."0930";
break;
default: break;
}
}
}
return $years;
}
/**
* $year 20201231 转为2020年报
* @param $year
*/
function yearToname($year){
switch (substr($year,4,4)){
case '1231':
return substr($year,0,4).'年报';
case '0930':
return substr($year,0,4).'三季';
case '0630':
return substr($year,0,4).'半年';
case '0331':
return substr($year,0,4).'一季';
default:
return substr($year,4,4);
}
}
?>
+252
View File
@@ -0,0 +1,252 @@
<?php
/*
上证指数:000001.SH
深证成指:399001.SZ
中小板指: 399005.SZ
创业板指:399006.SZ
*/
function getIndexData($ts_code,$day_st,$day_end){
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
#$ts_code = '000001.SH';
#$day_st = '20000101';
#$day_end = '20190701';
$where = " and trade_date>='".$day_st."'";
if($day_end) $where .= " and trade_date <='".$day_end."'";
$sql= <<<EOF
select trade_date, close from index_hist_pro where ts_code = '$ts_code' $where order by trade_date asc
EOF;
#echo $sql;
$result = $mysqli->query($sql);
$tDate=$idx=$data=array();
if($result && $result->num_rows>0) {
#$data = $result->fetch_all();
while($row=$result->fetch_assoc()){
$trade_date=substr($row['trade_date'],0,4).'-'.substr($row['trade_date'],4,2).'-'.substr($row['trade_date'],6,2);
$trade_date1=strtotime($row['trade_date']);
array_push($tDate,$trade_date);
array_push($idx,$row['close']);
array_push($data,array("value"=>array($trade_date,round($row['close'],2))));
}
}
#Free result and close connection.
$result->free();
$mysqli->close();
return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data);
}
/*
#LX: 序号 1-6,分别代表基金,QFII, 社保,券商,保险,信托
#share: vposition 市值 f10, sahreHDnum 股数 f9
*/
function getIhData($lx,$share,$day_st,$day_end){
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
/*
$where = " and rdate>='".$day_st."'";
if($day_end) $where .= " and rdate<='".$day_end."'";
if($share=='ShareHDNum' or $share=='vPosition') $shareSel='sum('.$share.')/100000000';
elseif($share=='VSRatio') $shareSel='vPosition/ShareHDNum';
$sql= <<<EOF
select rdate,$shareSel as ttl from ih_data where lx='$lx' $where group by rdate order by rdate
EOF;
*/
$where = " and ih_date>='".$day_st."'";
if($day_end) $where .= " and ih_date<='".$day_end."'";
if($share=='ShareHDNum' ) $shareSel="sum(f9)/100000000"; //持股数
elseif($share=='vPosition') $shareSel="sum(f10)/100000000"; //持股额
elseif($share=='VSRatio') $shareSel='f10/f9'; //每股价格
$sql= <<<EOF
select ih_date,$shareSel as ttl from ih_by_ts_code_ext where tp='$lx' $where group by ih_date order by ih_date
EOF;
$result = $mysqli->query($sql);
//echo $sql;
$tDate=$idx=$data=array();
if($result && $result->num_rows>0) {
#$data = $result->fetch_all();
while($row=$result->fetch_assoc()){
array_push($tDate,$row['ih_date']);
array_push($idx,$row['ttl']);
array_push($data,array("value"=>array($row['ih_date'],$row['ttl'])));
}
}
#Free result and close connection.
$result->free();
$mysqli->close();
return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data);
}
function lxDefine($lx){
switch($lx){
case 1: return "公募基金";
case 2: return "QFII";
case 3: return "社保基金";
case 4: return "券商持仓";
case 5: return "保险持仓";
case 6: return "信托持仓";
}
}
/*
上证指数:000001.SH
深证成指:399001.SZ
中小板指: 399005.SZ
创业板指:399006.SZ
*/
function codetocode($code){
switch($code){
case 'sh':
return '000001.SH';
case 'sz':
return '399001.SZ';
case 'zx':
return '399005.SZ';
case 'cy':
return '399006.SZ';
case 'all':
return '000002.SH';
}
}
/**
* @param $code
* @return string|void
*/
function codeToName($code){
switch($code){
case 'sh':
return '上证';
case 'sz':
return '深证';
case 'zx':
return '中小板';
case 'cy':
return '创业板';
case 'all':
return 'A股';
}
}
/**
* 名称 类型 描述
trade_date str 交易日期
ggt_ss float 港股通(上海)
ggt_sz float 港股通(深圳)
hgt float 沪股通(百万元)
sgt float 深股通(百万元)
north_money float 北向资金(百万元)
south_money float 南向资金(百万元)
* @param $code
* @return false|string
*/
function hsgtConv($code){
switch ($code){
case 'ggt_ss':
return '港股通(上海)';
case 'ggt_sz':
return '港股通(深圳)';
case 'hgt':
return '沪股通';
case 'sgt':
return '深股通';
case 'north_money':
return '北向资金';
case 'south_money':
return '南向资金';
default:
return false;
}
}
function hkholdConv($code){
switch ($code){
case 'ratio':
return '持股比例(%)';
case 'vol':
return '持股数(万)';
default:
return false;
}
}
/*
#item: f9:持股数 f10:持股额 f11:占总股本比例 f12:占流通股比例
#LX: tp字段: 序号 1-6,分别代表基金,QFII, 社保,券商,保险,信托
*/
function getIhDataByStock($ts_code,$item,$lx,$day_st,$day_end){
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
$where = " and ih_date>'".$day_st."'";
if($day_end) $where .= " and ih_date<'".$day_end."'";
if($lx) $where .= " and tp='".$lx."'";
switch(strtoupper($item)){
case 'F9':
$item_sel = 'sum('.$item.')/10000'; #单位万股
break;
case 'F10':
$item_sel = 'sum('.$item.')/10000'; #单位万元
break;
case 'F11':
case 'F12':
$item_sel = 'sum('.$item.')'; #单位%
break;
}
$sql= <<<EOF
select ts_code,ih_date,$item_sel as ttl from ih_by_ts_code_ext where ts_code='$ts_code' $where group by ih_date order by ih_date asc
EOF;
$result = $mysqli->query($sql);
#echo $sql;
$tDate=$idx=$data=array();
if($result && $result->num_rows>0) {
#$data = $result->fetch_all();
while($row=$result->fetch_assoc()){
array_push($tDate,$row['ih_date']);
array_push($idx,$row['ttl']);
array_push($data,array("value"=>array($row['ih_date'],$row['ttl'])));
}
}
$data_last= round($idx[count($idx)-1],1);
$data_max= round(max($idx),1);
$data_min= round(min($idx),1);
if(count($idx)>0) $data_avg= round(array_sum($idx)/count($idx),1);
else $data_avg=null;
#Free result and close connection.
$result->free();
$mysqli->close();
return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}
function getMoneyFlowData($itm, $day_st,$day_end, $stacked){
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
if($stacked==1) $tb = 'moneyflow_hsgt_pro_ext';
else $tb = 'moneyflow_hsgt_pro';
$where = " trade_date>='".$day_st."'";
if($day_end) $where .= " and trade_date <='".$day_end."'";
$sql= <<<EOF
select trade_date, $itm as itm from $tb where $where order by trade_date asc
EOF;
#echo $sql;
$result = $mysqli->query($sql);
$tDate=$data=array();
if($result && $result->num_rows>0) {
while($row=$result->fetch_assoc()){
$trade_date=date('Y-m-d',strtotime($row['trade_date']));
array_push($tDate,$row['itm']/100);
array_push($data,array("value"=>array($trade_date,round($row['itm']/100,2))));
}
}
#Free result and close connection.
$result->free();
$mysqli->close();
$data_last= round($tDate[count($tDate)-1],2);
$data_max= round(max($tDate),2);
$data_min= round(min($tDate),2);
if(count($tDate)>0) $data_avg= round(array_sum($tDate)/count($tDate),2);
return array('tDate'=>$tDate,'data'=>$data,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}
?>
+19
View File
@@ -0,0 +1,19 @@
<?php
function getEstateData($city='宁波',$fDate,$toDate){
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
$sql=<<<EOF
SELECT city, listdate,sum(nums) as num FROM `estate_listing`
where listdate>='$fDate' and listdate<='$toDate' and city='$city' group by listdate
EOF;
$result = $mysqli->query($sql);
$data=array();
if($result && $result->num_rows>0) {
while($row = $result->fetch_assoc()){
array_push($data,array("value"=>array($row['listdate'],$row['num'])));
}
}
return $data;
}
?>
+324
View File
@@ -0,0 +1,324 @@
<?php
include_once __DIR__."/getData.inc.php"; //类外调用方法
include_once __DIR__."/getBasic.inc.php"; //类外调用方法
class getFinance
{
private $url = "http://api.waditu.com";
private $token = '1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea';
public $ts_code = '002273.SZ'; //set ts_code default
public $httpjsonStr; //json string send to http_post_json
public $finDate;
public $preFinDate;
public $param = array();
private $unitFactor = 100000000; //单位因子,除以后单位亿
function __construct()
{
$this->param['token'] = $this->token;
}
/**
* PHP发送Json对象数据
*
* @param $url 请求url
* @param $jsonStr 发送的json字符串,来自$param转换
* @return array
*/
function http_post_json()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->httpjsonStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($this->httpjsonStr)
)
);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array($httpCode, $response);
}
/**
* @param $ts_code
* @param $finDate 财报日期 如一季报日期:20220331
*/
function getFinanceData()
{
$this->ts_code = ts_code_conv($this->ts_code);
$balance = $this->getBalance();
$pre_balance = $this->getPreBalance();
$income = $this->getIncome();
$cash = $this->getCashflow();
$data = array();
$data['ts_code'] = $this->ts_code;
$data['period'] = $this->finDate;
$data['--运营数据--'] = ''; //空行
$data['现金额-亿'] = $cash['c_cash_equ_end_period'][0] / $this->unitFactor;
$data['现金占比率'] = $cash['c_cash_equ_end_period'][0] / $balance['total_assets'][0];
$data['存货-亿'] = $balance['inventories'][0] / $this->unitFactor;
$data['存货占比率'] = $balance['inventories'][0] / $balance['total_assets'][0];
#应收账票
$tmp = 0;
if ($balance['accounts_receiv'][0]) $tmp += $balance['accounts_receiv'][0];
if ($balance['notes_receiv'][0]) $tmp += $balance['notes_receiv'][0];
$data['应收账票-亿'] = $tmp / $this->unitFactor;
$data['应收账票占比率'] = $tmp / $balance['total_assets'][0];
#预付款
$tmp = 0;
if ($balance['prepayment'][0]) $tmp += $balance['prepayment'][0];
$data['预付款-亿'] = $tmp / $this->unitFactor;
#预付占比
$data['预付款占比率'] = $tmp / $balance['total_assets'][0];
#运营占比
$tmp = 0;
if ($cash['c_cash_equ_end_period'][0]) $tmp += $cash['c_cash_equ_end_period'][0];
if ($balance['inventories'][0]) $tmp += $balance['inventories'][0];
if ($balance['accounts_receiv'][0]) $tmp += $balance['accounts_receiv'][0];
if ($balance['notes_receiv'][0]) $tmp += $balance['notes_receiv'][0];
if ($balance['prepayment'][0]) $tmp += $balance['prepayment'][0];
$data['运营占比率'] = $tmp / $balance['total_assets'][0];
$data['--资产分布--'] = ''; //空行
if ($balance['fix_assets'][0]) $tmp = $balance['fix_assets'][0] / $this->unitFactor;
else $tmp = "";
$data['固定资产-亿'] = $tmp;
if ($balance['fix_assets'][0]) $tmp = $balance['fix_assets'][0] / $balance['total_assets'][0];
else $tmp = "";
$data['固定资产占比率'] = $tmp;
$data['无形资产-亿'] = $balance['intan_assets'][0] / $this->unitFactor;
$data['无形资产占率'] = $balance['intan_assets'][0] / $balance['total_assets'][0];
$tmp = 0;
if ($balance['lt_eqt_invest'][0]) $tmp = $balance['lt_eqt_invest'][0];
$data['股权投资-亿'] = $tmp / $this->unitFactor;
$data['股权投资占比率'] = $tmp / $balance['total_assets'][0];
$tmp = 0;
if ($balance['fix_assets'][0]) $tmp += $balance['fix_assets'][0];
if ($balance['intan_assets'][0]) $tmp += $balance['intan_assets'][0];
if ($balance['lt_eqt_invest'][0]) $tmp += $balance['lt_eqt_invest'][0];
$data['投资占比率'] = $tmp / $balance['total_assets'][0];
$data['--负债分布--'] = ''; //空行
$tmp = 0;
if ($balance['acct_payable'][0]) $tmp += $balance['acct_payable'][0];
if ($balance['notes_payable'][0]) $tmp += $balance['notes_payable'][0];
if ($balance['adv_receipts'][0]) $tmp += $balance['adv_receipts'][0];
#tmp = balance['acct_payable'][0]+balance['notes_payable'][0]+balance['adv_receipts'][0]
$data['经营负债-亿'] = $tmp / $this->unitFactor;
$data['经营负债占比率'] = $tmp / $balance['total_assets'][0];
$tmp = 0;
if ($balance['st_borr'][0]) $tmp += $balance['st_borr'][0];
if ($balance['lt_borr'][0]) $tmp += $balance['lt_borr'][0];
if ($balance['bond_payable'][0]) $tmp += $balance['bond_payable'][0];
$data['金融负债-亿'] = $tmp / $this->unitFactor;
$data['金融负债占比率'] = $tmp / $balance['total_assets'][0];
$zcfz = ($balance['total_cur_liab'][0] + $balance['total_ncl'][0]) / $balance['total_assets'][0];
$data['资产负债率'] = $zcfz;
$data['--运营能力--'] = ''; //空行
$totalDays=$this->getTotalDays();
@$days_1 = $totalDays / ($income['oper_cost'][0] / (($pre_balance['inventories'][0] + $balance['inventories'][0]) / 2));
if(is_nan($days_1)) $days_1=0; //solve division by zero warning
//echo "\$days_1:".$days_1;
$data['存货周转天数'] = $days_1;
if(!$pre_balance['accounts_receiv'][0]) $days_2 = 0;
elseif(!$balance['accounts_receiv'][0]) $days_2 = 0;
else $days_2 = $totalDays/($income['revenue'][0]/(($pre_balance['accounts_receiv'][0]+$balance['accounts_receiv'][0])/2));
$data['应收周转天数'] = $days_2;
$data['营业周期'] = $days_1+$days_2;
$data['--管理费分布--'] = ''; //空行
$tmp = ($income['revenue'][0]-$income['oper_cost'][0])/$income['revenue'][0];
$data['毛利额'] = ($income['revenue'][0]-$income['oper_cost'][0])/$this->unitFactor;;
$data['毛利率'] = $tmp;
$data['营业税金率'] = $income['biz_tax_surchg'][0]/$income['revenue'][0];
$data['销售费用率'] = $income['sell_exp'][0]/$income['revenue'][0];
$data['研发费用率'] = $income['rd_exp'][0]/$income['revenue'][0];
$data['管理费用率'] = $income['admin_exp'][0]/$income['revenue'][0];
$data['净利润'] = $income['n_income'][0]/$this->unitFactor;
$data['净利润率'] = $income['n_income'][0]/$income['revenue'][0];
$data['--权益及回报率--'] = ''; //空行
$data['总资产-亿'] = $balance['total_assets'][0]/$this->unitFactor;
$data['销售收入-亿'] =$income['revenue'][0]/$this->unitFactor;
$data['总资产周转率'] = $income['revenue'][0]/$balance['total_assets'][0];
$zchb = $income['n_income'][0]/$balance['total_assets'][0];
$data['总资产回报率']=$zchb;
$data['权益乘数']=1/(1-$zcfz);
$data['净资产回报率']=$zchb*(1/(1-$zcfz));
foreach ($data as $key=>$val){
if(is_numeric($val)) {
if(mb_substr($key,-1,1)=='率') $rt[$key]= round($val*100,2).'%'; //最后一个字为率,则去百分比%
else $rt[$key]= round($val,2);
}
else $rt[$key]=$val;
}
return $rt;
}
function getFinanceJson()
{
$d = $this->getFinanceData();
return json_encode($d);
}
function getBalance()
{
$this->param['api_name']='balancesheet';
## 资产负债表
$fields = 'ts_code';
$fields .= ',end_date'; #=$finDate
$fields .= ',total_assets'; #总资产
$fields .= ',fix_assets'; #固定资产
$fields .= ',intan_assets'; #无形资产
$fields .= ',lt_eqt_invest'; #长期股权投资
$fields .= ',inventories'; #存货
$fields .= ',accounts_receiv'; #应收账款
$fields .= ',notes_receiv'; #应收票据
$fields .= ',prepayment'; #预付款
$fields .= ',acct_payable'; #应付账款
$fields .= ',notes_payable'; #应付票据
$fields .= ',adv_receipts'; #预收款
$fields .= ',st_borr'; #短期借款
$fields .= ',lt_borr'; #长期借款
$fields .= ',bond_payable'; #应付债券
$fields .= ',total_cur_liab'; #流动负债合计
$fields .= ',total_ncl'; #非流动负债合计
$this->param['params'] = array('ts_code' => ts_code_conv($this->ts_code),
'period'=>$this->finDate);
$this->param['fields']=$fields;
$this->httpjsonStr=json_encode($this->param);
list($returnCode, $returnContent) = $this->http_post_json();
$arr = json_decode($returnContent,true);
return $this->mergeArr($arr['data']);
}
/**
* #期初的日期: 上一年的年底的数据
* @return mixed
*/
function getPreBalance()
{
$this->param['api_name']='balancesheet';
$this->preFinDate=(substr($this->finDate,0,4)-1).'1231'; //上一年的年底日期;
## 资产负债表
$fields = 'ts_code';
$fields .= ',end_date'; #=$finDate
$fields .= ',inventories'; #存货
$fields .= ',accounts_receiv'; #应收账款
$fields .= ',notes_receiv'; #应收票据
$this->param['params'] = array('ts_code' => ts_code_conv($this->ts_code),
'period'=>$this->preFinDate);
$this->param['fields']=$fields;
$this->httpjsonStr=json_encode($this->param);
list($returnCode, $returnContent) = $this->http_post_json();
$arr = json_decode($returnContent,true);
return $this->mergeArr($arr['data']);
}
function getIncome()
{
$this->param['api_name']='income';
#利润表
#销售毛利率=(营业收入-营业成本)/营业收入 注意非总收入和总成本
$fields = 'ts_code';
$fields .= ',end_date'; #=period
$fields .= ',revenue'; #营业收入
$fields .= ',oper_cost'; #营业成本
$fields .= ',biz_tax_surchg'; #营业税金及附加
$fields .= ',sell_exp'; #销售费用
$fields .= ',fin_exp'; #财务费用
$fields .= ',admin_exp'; #管理费用
$fields .= ',n_income'; #净利润
$fields .= ',rd_exp'; #研发费用
$this->param['params'] = array('ts_code' => ts_code_conv($this->ts_code),
'period'=>$this->finDate);
$this->param['fields']=$fields;
$this->httpjsonStr=json_encode($this->param);
list($returnCode, $returnContent) = $this->http_post_json();
$arr = json_decode($returnContent,true);
return $this->mergeArr($arr['data']);
}
function getCashflow()
{
$this->param['api_name']='cashflow';
#现金流量表
$fields = 'ts_code';
$fields .= ',end_date'; #=period
$fields .= ',c_cash_equ_end_period';#期末现金及现金等价物余额
$fields .= ',end_bal_cash'; #现金的期末余额
$this->param['params'] = array('ts_code' => ts_code_conv($this->ts_code),
'period'=>$this->finDate);
$this->param['fields']=$fields;
$this->httpjsonStr=json_encode($this->param);
list($returnCode, $returnContent) = $this->http_post_json();
//echo $returnContent;
$arr = json_decode($returnContent,true);
return $this->mergeArr($arr['data']);
}
/**
* Array ( [fields] => Array ( [0] => ts_code [1] => end_date [2] => notes_receiv [3] => accounts_receiv [4] => inventories )
* [items] => Array ( [0] => Array ( [0] => 002223.SZ [1] => 20201231 [2] => [3] => 546811497.99 [4] => 968427866.64 )
* [1] => Array ( [0] => 002223.SZ [1] => 20201231 [2] => [3] => 546811497.99 [4] => 968427866.64 ) )
* transfor to:
* Array (ts_code=>array([0]=>002273.SZ [1]=>002273.SZ) notes_receiv=>array([0]=>546811497.99 [1]=>546811497.99)... )
* @param $data
*/
function mergeArr($data)
{
$rt = array();
for($i=0;$i<count($data['fields']);$i++){
for($j=0;$j<count($data['items']);$j++)
$rt[$data['fields'][$i]][]=$data['items'][$j][$i];
}
return $rt;
}
/**
* 根据当前财报日期,获取营业周期的基本天数
* 天数按会计算法?90/180/270/360
*/
function getTotalDays(){
if($this->finDate) $dateCut=substr($this->finDate,4,4);
switch ($dateCut){
case '0331':
return 90;
case '0630':
return 180;
case '0930':
return 270;
case '1231':
return 360;
}
}
}
?>
+111
View File
@@ -0,0 +1,111 @@
<?php
ob_start();
include_once "../include/config.inc.php"; //Include config file;
$db = new ora();
$title="计划设置";
include_once "head.php"; //include head file
echo $hr;
$t = 1; //initial type to 1;
if($_REQUEST['doSubmit']) bom_op($_REQUEST['t']); //operate when submit
if($_REQUEST['bomid'] and !$_REQUEST['doSubmit']) {
$bom = bom_data_by_id();
$_REQUEST["bom"] = $bom['BOMNAME'];
$_REQUEST["bomid"] = $bom['BOMID'];
$_REQUEST["bomnote"] = $bom['FNOTE'];
$_REQUEST["flowid"] = $bom['FLOWID'];
$_REQUEST["ver"] = $bom['VER'];
$t = 0;
}
?>
<link rel="stylesheet" href="../lib/layui/css/layui.min.css">
<div id="mainContent">
<h2><?php echo $title; ?></h2>
<form name="formhead" id="formhead" method="post" enctype="multipart/form-data" >
<div class="layui-inline">
<input type="file" id="file" name="file" class="layui-btn">
</div>
<div class="layui-inline">
<button type="button" class="layui-btn" id="btnUpload">
<i class="layui-icon">&#xe67c;</i>EXCEL上传验证
</button>
</div>
</form>
<form name="form2" id="form2" method="post" >
<div class="stay_center" id="fblock" style="display: none">
<div style="margin-top:10px;" id="ftext" class="layui-col-md12"></div>
<input type="hidden" name="fpath" id="fpath" value="">
<div class="layui-inline">
<input type="button" id="btnExcel" value="处理上传文件" class="layui-btn">
</div>
</div>
</form>
<script type="text/javascript">
$(function () {
$("#btnUpload").click(function () {
console.log("Upload button clicked!");
var formData = new FormData($('#formhead')[0]);
$.ajax({
type: 'post',
url: "http://192.168.10.21/cimv2/cim/bom/upload.php", //上传文件的请求路径必须是绝对路劲
data: formData,
cache: false,
processData: false,
contentType: false,
}).success(function (data) {
afterUpload(data);
}).error(function () {
alert("上传失败");
});
});
});
function afterUpload(data){
var arr = $.parseJSON(data);
if(arr['status']!=1) {
alert(arr.msg);
return false;
}
$("#file").val(''); //set input(file) to null
$("#fblock").css("display","block");
$("#ftext").html("文件上传成功!点击下面按钮开始执行<br />"+arr['fpath']+"<br />");
$("#fpath").val(arr['fpath']);
}
$(function () {
$("#btnExcel").click(function () {
console.log("Process excel button clicked!");
$("#btnExcel").attr("disabled",true);
console.log("Button disabled!");
var formData = new FormData($('#form2')[0]);
$.ajax({
type: 'post',
url: "http://192.168.10.21/cimv2/cim/bom/excel.php", //上传文件的请求路径必须是绝对路劲
data: formData,
cache: false,
processData: false,
contentType: false,
}).success(function (data) {
excelProcess(data);
$("#btnExcel").attr("disabled",false);
console.log("Button enabled!");
console.log("Done everything!");
}).error(function () {
alert("处理失败");
});
});
});
function excelProcess(data){
console.log("Excel data upload successful!");
console.log(data);
var arr = $.parseJSON(data);
var htmlmsg;
for(i = 0;i < arr.msg.length;i++) htmlmsg += arr['msg'][i];
console.log("htmlmsg proceed!");
$("#ftext").html(htmlmsg);
}
</script>
</div>
<?php
include_once "foot.php";
?>
+265
View File
@@ -0,0 +1,265 @@
<?php
/**
* PHP发送Json对象数据
*
* @param $url 请求url
* @param $jsonStr 发送的json字符串
* @return array
*/
function http_post_json($url, $jsonStr)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($jsonStr)
)
);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array($httpCode, $response);
}
/**
* 获取复权因子
* @return array
*/
function getAdj(){
$url = "http://api.waditu.com";
$param['api_name']='adj_factor';
$param['token']='1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea';
$param['params'] = array('ts_code' => ts_code_conv($_REQUEST['ts_code']),
'start_date'=>str_replace('-','',$_REQUEST['t_start']),
'end_date'=>str_replace('-','',$_REQUEST['t_end'])
);
$param['fields'] ="";
$jsonStr=json_encode($param);
list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
$arr = json_decode($returnContent,true);
$items = $arr['data']['items'];
$lastAdj=$items[0][2];
foreach ($items as $t){
list($ts_code,$date,$adj)=$t;
$rt[$date]=$adj/$lastAdj;
}
return $rt;
}
/**
* 获取个股融资融券余额信息
* @return mixed
*/
function getMarginByCode(){
$url = "http://api.waditu.com";
$param['api_name']='margin_detail';
$param['token']='1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea';
$param['params'] = array('ts_code' => ts_code_conv($_REQUEST['ts_code']),
'start_date'=>str_replace('-','',$_REQUEST['t_start']),
'end_date'=>str_replace('-','',$_REQUEST['t_end'])
);
$param['fields'] ="";
$jsonStr=json_encode($param);
list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
$arr = json_decode($returnContent,true);
return $arr['data'];
}
/**
* @param $exchange SSE OR SZSE, set null for all
* @return mixed
*/
function getMarginAll($exchange){
$url = "http://api.waditu.com";
$param['api_name']='margin_detail';
$param['token']='1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea';
$param['params'] = array(
'start_date'=>str_replace('-','',$_REQUEST['t_start']),
'end_date'=>str_replace('-','',$_REQUEST['t_end']),
'exchange_id'=>$exchange
);
$param['fields'] ="";
$jsonStr=json_encode($param);
list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
$arr = json_decode($returnContent,true);
return $arr['data'];
}
/**
* 沪深港通资金流向
* @return mixed
*/
function getMoneyFlowHSGT(){
$url = "http://api.waditu.com";
$param['api_name']='moneyflow_hsgt';
$param['token']='1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea';
$param['params'] = array(
'start_date'=>'20200601',
'end_date'=>date('Ymd')
);
$param['fields'] ="";
$jsonStr=json_encode($param);
list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
$arr = json_decode($returnContent,true);
return $arr['data'];
}
/**
* 获取A股个股香港资金持股每日数据
* @return mixed
*/
function getHKHoldByCode(){
$url = "http://api.waditu.com";
$param['api_name']='hk_hold';
$param['token']='1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea';
$param['params'] = array(
'ts_code' => ts_code_conv($_REQUEST['ts_code']),
'start_date'=>str_replace('-','',$_REQUEST['t_start']),
'end_date'=>str_replace('-','',$_REQUEST['t_end'])
);
$param['fields'] ="";
$jsonStr=json_encode($param);
list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
$arr = json_decode($returnContent,true);
return $arr['data'];
}
/**
* 使用复权因子对股价和成交股数进行复权
* @param $adj
* @param $data
* @return mixed
*/
function adjData($adj,$data){
$num = count($data);
for($i=0;$i<$num;$i++){
$t = str_replace('-','',$data[$i]['tdate']);
$data[$i]['tprice']=round($data[$i]['tprice']*$adj[$t],3);
$data[$i]['tvol']=round($data[$i]['tvol']/$adj[$t],0);
}
return $data;
}
/**
*
0] => trade_date
[1] => ts_code
[2] => rzye
[3] => rqye
[4] => rzmre
[5] => rqyl
[6] => rzche
[7] => rqchl
[8] => rqmcl
[9] => rzrqye
https://tushare.pro/document/2?doc_id=58
*/
function marginByCodeReform($data){
$data['items']=array_reverse($data['items']);
foreach($data['items'] as $rec){
$dataRT[]=array('value'=>array(date('Y-m-d',strtotime($rec[0])),$rec[9]/10000/10000));
$val[]=$rec[9]/10000/10000;
}
$data_last= round($val[count($val)-1],2);
$data_max= round(max($val),2);
$data_min= round(min($val),2);
if(count($val)>0) $data_avg= round(array_sum($val)/count($val),2);
else $data_avg=null;
return array('data'=>$dataRT,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}
/**
* 计算累积值
* @param $data
* @return array
*/
function moneyFlowStacked($data){
$keys=array_keys($data['fields']);
$num = count($data['items']);
foreach ($keys as $key) {
$tmp = 0;
for($i=0; $i<$num; $i++){
//keep trade_date field NOT changed.
if($key > 0)$tmp += $data['items'][$i][$key];
else $tmp = $data['items'][$i][$key];
$items[$i][$key]=$tmp;
}
}
return array('fields'=>$data['fields'],'items'=>$items);
}
/**
* 根据日期截取数据
* @param $data
* @param $s start date yyyymmdd
* @param $e end date yyyymmdd
* @return array|false
*/
function moneyFlowDateFilter($data,$s,$e){
if($s>$e) return false;
$num = count($data['items']);
$items = array();
for($i=0;$i<$num;$i++){
if($data['items'][$i][0]>= $s and $data['items'][$i][0]<= $e)
$items[]=$data['items'][$i];
}
return array('fields'=>$data['fields'],'items'=>$items);
}
/**
*$hsgt :
[0] => trade_date
[1] => ggt_ss
[2] => ggt_sz
[3] => hgt
[4] => sgt
[5] => north_money
[6] => south_money
*/
function moneyFlowReform($data,$hsgt){
$data['items']=array_reverse($data['items']);
$key = array_search($hsgt,$data['fields']);
foreach($data['items'] as $rec){
$dataRT[]=array('value'=>array(date('Y-m-d',strtotime($rec[0])),$rec[$key]/100));
$val[]=$rec[$key]/100; //单位:亿元
}
$data_last= round($val[count($val)-1],2);
$data_max= round(max($val),2);
$data_min= round(min($val),2);
if(count($val)>0) $data_avg= round(array_sum($val)/count($val),2);
else $data_avg=null;
return array('data'=>$dataRT,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}
/**
* $hkhold:
* 0 code
* 1 trade_date
* 2 ts_code
* 3 name
* 4 vol
* 5 ratio
* 6 exchange
*
*/
function hkHoldReform($data,$hkhold){
//print_r($data);
$data['items']=array_reverse($data['items']);
$key = array_search($hkhold,$data['fields']);
foreach($data['items'] as $rec){
if($hkhold=='vol') $rec[$key] = $rec[$key]/10000; //万股
$dataRT[]=array('value'=>array(date('Y-m-d',strtotime($rec[1])),$rec[$key]));
$val[]=$rec[$key];
}
$data_last= round($val[count($val)-1],2);
$data_max= round(max($val),2);
$data_min= round(min($val),2);
if(count($val)>0) $data_avg= round(array_sum($val)/count($val),2);
else $data_avg=null;
return array('data'=>$dataRT,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}
+151
View File
@@ -0,0 +1,151 @@
<?php
/**
* @param $ts_code: stock code
* @param $where: add select condition you need.
* @return array: return stock trade recode history data;
*/
function trade_rec($ts_code, $day_st, $day_end,$where = ''): array
{
global $mysqli;
$tmp=explode('.',$ts_code);
$ts_code = $tmp[0];
$day_end = ($day_end)?$day_end:date('Y-m-d');
$where = $where." and tdate>= '{$day_st}' and tdate<='{$day_end}' and tprice>0"; //担保转出的时候,可能tprice<0
if($_REQUEST['t_vendor']=='方正证券') {
$sql = <<< EOF
select * from trade_record where ts_code = '$ts_code' $where and length(trade_id)=5 order by tdate asc,ttime asc
EOF;
} elseif($_REQUEST['t_vendor']=='长江证券') {
$sql = <<< EOF
select * from trade_record_cj where ts_code = '$ts_code' $where order by tdate asc,ttime asc
EOF;
}
$result = $mysqli->query($sql) or die($sql);
return $result->fetch_all(MYSQLI_ASSOC);
}
/**
* @param $data : data get from db
* @param $flgType : 2 of flg type: 买入,卖出,
* @return array
*/
function recDataSort($data,$flgType):array {
$dataNum=count($data);
$rtData=$note=$rtVol=$rtPrice=array();
for($i=0;$i<$dataNum;$i++){
if($flgType !='' and $data[$i]['flg']!=$flgType) continue; //$flgType is null means all data matches
$rtData[] = array("value"=>array($data[$i]['tdate'],$data[$i]['tprice']));
$rtDataVol[] = array("value"=>array($data[$i]['tdate'],abs($data[$i]['tvol'])));
$rtVol[] = $data[$i]['tvol'];
$rtPrice[] = $data[$i]['tprice'];
$note[] = "{$data[$i]['tprice']} {$data[$i]['flg']} {$data[$i]['ts_name']} {$data[$i]['tvol']} 股,成交金额 {$data[$i]['tamount']}";
}
return array('data'=>$rtData, 'data2'=>$rtDataVol,'note'=>$note, 'tvol'=>$rtVol, 'tprice'=>$rtPrice);
}
/**
* @param $vol : trade volume array
* @param $price : trade price array
* @return array|false
*/
function avePrice($vol,$price){
$numVol = count($vol);
$numPrice = count($price);
if($numPrice!=$numVol or $numVol==0) return false;
$ttlVol=array_sum($vol);
$ttlAmt=0; //total amount
for($i=0;$i<$numVol;$i++){
$ttlAmt += $vol[$i]*$price[$i];
}
$aveprice=round($ttlAmt/$ttlVol,2);
return array('avePrice'=>$aveprice,'ttlVol'=>$ttlVol,);
}
function tradeSummary($dataBuy,$dataSell,$dataAll):array{
$buyNum = count($dataBuy);
$sellNum = count($dataSell);
$allNum = count($dataAll);
$dataBuyReverse = array_reverse($dataBuy,false); //反向重排数组,key值不保留
$sellVol = $sellAmt = $sellTaxAll =0;
$buyVol = $buyAmt = $buyTaxAll = 0;
$buyVolRev = $buyAmtRev = $buyAmtRevFix = $buyPriceRevFix = 0;
for($i=0;$i<$sellNum;$i++){
$sellVol += $dataSell[$i]['tvol'];
$sellAmt += $dataSell[$i]['tamount'];
if($_REQUEST['t_vendor']=='方正证券')
$sellTaxAll += $dataSell[$i]['commission'];
$sellTaxAll += $dataSell[$i]['tax1'];
$sellTaxAll += $dataSell[$i]['tax2'];
$sellTaxAll += $dataSell[$i]['tax3'];
}
for($i=0;$i<$buyNum;$i++){
$buyVol += $dataBuy[$i]['tvol'];
$buyAmt += $dataBuy[$i]['tamount'];
if($_REQUEST['t_vendor']=='方正证券')
$buyTaxAll += $dataSell[$i]['commission'];
$buyTaxAll += $dataBuy[$i]['tax2'];
$buyTaxAll += $dataBuy[$i]['tax3'];
$buyTaxAll += $dataBuy[$i]['tax1'];
if($buyVolRev<abs($sellVol)) {
$buyVolRev += $dataBuyReverse[$i]['tvol'];
$buyAmtRev += $dataBuyReverse[$i]['tamount'];
}
}
if($buyVolRev >= $sellVol) {
$buyAmtRevFix = $buyAmtRev;
$netTAmt = $sellAmt - $buyAmtRevFix;
//按价格验算净收入
if($buyVolRev) $buyPriceRevFix = $buyAmtRev/$buyVolRev;
else $buyPriceRevFix = 0;
$netTAmtCal = $sellAmt-abs($buyPriceRevFix*min(abs($sellVol),$buyVolRev));
$buyPriceRevFix = round($buyPriceRevFix,2);
$netTAmtCal = round($netTAmtCal,0);
//差价>100表示$buyVolRev 与$sellVol差异较大
if(abs($netTAmtCal-$netTAmt)>100)
$netTAmtArr = array("T买成本" => $buyPriceRevFix, "T买股数" => $buyVolRev,"T近似收益" => $netTAmtCal);
else
$netTAmtArr = array("T买成本" => $buyPriceRevFix, "T买股数" => $buyVolRev,"做T收益" => round($netTAmt,0));
}
$buyAvePrice = round($buyAmt/$buyVol,2);
if($sellVol) $sellAvePrice = abs(round($sellAmt/$sellVol,2));
else $sellAvePrice = 0;
$netBuyVol = $buyVol + $sellVol;
$netBuyAmt = $buyAmt - $sellAmt;
$recentPrice = recentPrice($_REQUEST['ts_code']); //最新价格,前一天收盘价
$stockCost =($netBuyVol>0)?round(($netBuyAmt+$sellTaxAll+$buyTaxAll)/$netBuyVol,2):'--'; //持股成本
$currentProfit =($netBuyVol>0)?round(($recentPrice['close'] - $stockCost) * $netBuyVol,2):'--'; //当前浮动盈亏;
$netTAmtArr = array_merge($netTAmtArr, array("最新价格"=>$recentPrice['close'],"浮动盈亏" => $currentProfit));
$rtArr =array("买入次数"=>$buyNum,"买入股数"=>$buyVol,"买入金额"=>$buyAmt,"买入均价"=>$buyAvePrice,"买入税费"=>$buyTaxAll,
"卖出次数"=>$sellNum,"卖出股数"=>abs($sellVol),"卖出金额"=>$sellAmt,"卖出均价"=>$sellAvePrice,"卖出税费"=>$sellTaxAll,
"当前股数"=>$netBuyVol,"持股金额"=>$netBuyAmt, "持股成本"=>$stockCost);
return array_merge($rtArr,$netTAmtArr);
}
function recentPrice($ts_code){
global $mysqli;
$sql = "SELECT close FROM `stock_his_pro` where ts_code='".ts_code_conv($ts_code)."' and trade_date=(select max(trade_date) from stock_his_pro)";
$result = $mysqli->query($sql) or die($sql);
$rt = $result->fetch_all(MYSQLI_ASSOC); //MYSQLI_ASSOC object $rt[0]['close']
return $rt[0]; //get arr['close']
}
/**
* reform date to yyyymmdd
* @param $date
* @return false|string
*/
function reformDate($date){
return date('Ymd',strtotime($date));
}
+71
View File
@@ -0,0 +1,71 @@
<?php
ini_set("display_errors","1");
header("content-type:text/html;charset=utf-8");
//设置时区
date_default_timezone_set('PRC');
//获取文件名
$filename = $_FILES['file']['name'];
//获取文件临时路径
$temp_name = $_FILES['file']['tmp_name'];
//获取大小
$size = $_FILES['file']['size'];
//获取文件上传码,0代表文件上传成功
$error = $_FILES['file']['error'];
//判断文件大小是否超过设置的最大上传限制
if ($size > 20*1024*1024){
//
//echo "<script>alert('文件大小超过20M大小');window.history.go(-1);</script>";
echo json_encode(array(
"status" => "-2",
"data"=> $_FILES['file'],
"msg" => "文件大小超过20MB!",
));
exit();
}
//phpinfo函数会以数组的形式返回关于文件路径的信息
//[dirname]:目录路径[basename]:文件名[extension]:文件后缀名[filename]:不包含后缀的文件名
$arr = pathinfo($filename);
//获取文件的后缀名
$ext_suffix = $arr['extension'];
//设置允许上传文件的后缀
$allow_suffix = array('xls');
//判断上传的文件是否在允许的范围内(后缀)==>白名单判断
if(!in_array($ext_suffix, $allow_suffix)){
//window.history.go(-1)表示返回上一页并刷新页面
//echo "<script>alert('上传的文件类型只能是jpg,gif,jpeg,png,xls');window.history.go(-1);</script>";
echo json_encode(array(
"status" => "-1",
"rows"=>$arr,
"msg" => "仅支持上传文件类型: xls!",
));
exit();
}
//检测存放上传文件的路径是否存在,如果不存在则新建目录
$uploadDir = __DIR__ . '/../uploads/';
if (!file_exists($uploadDir)){
mkdir($uploadDir);
}
//为上传的文件新起一个名字,保证更加安全
$new_filename = date('YmdHis',time()).rand(100,1000).'.'.$ext_suffix;
//将文件从临时路径移动到磁盘
if (move_uploaded_file($temp_name, $uploadDir.$new_filename)){
//echo "<script>alert('文件上传成功!');window.history.go(-1);</script>";
echo json_encode(array(
"status" => "1",
"data"=>$arr,
"fpath"=>$uploadDir.$new_filename,
"msg" => "File upload success!",
));
}else{
//echo "<script>alert('文件上传失败,错误码:$error');</script>";
echo json_encode(array(
"status" => "-1",
"data"=>$ext_suffix,
"fpath"=>$uploadDir,
"file"=>$_FILES['file'],
"msg" => "文件上传失败,错误码:$error",
"e"=>"error",
));
}