首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读取JSON文件,基本计算,并写入另一个JSON文件

读取JSON文件,基本计算,并写入另一个JSON文件
EN

Code Review用户
提问于 2019-03-16 01:40:08
回答 1查看 117关注 0票数 -1

SectorController使用API中的分钟数据计算股票交易所市场部门业绩的权重系数(例如,如果一组股票在过去5分钟内上涨,则系数为正,如果不是,则为负值,从-1到+1不等)。大多数计算都是基于其他脚本的,这对于本审查来说并不是必要的。

如果可能的话,你能好心地复习一下这门课,并帮助我把它做得更快吗?

脚本

代码语言:javascript
复制
class SectorController
{

  /**
  *
  * @var a string of iextrading base URL
  */

  const BASE_URL = "https://api.iextrading.com/1.0/"; 

  /**
  *
  * @var a string of target path and query
  */

  const TARGET_QUERY = "stock/market/batch?symbols=";


  /**
  *
  * @var a string for backend path for every sector
  */

  const EACH_SECTOR_DIR_PREFIX = "/../../dir/dir/dir/dir-";


  /**
  *
  * @var a string for backend path for index sector
  */

  const INDEX_SECTOR_DIR_PREFIX = "/../../dir/dir/dir/dir/";


  /**
  *
  * @var a string for live data path
  */

  const LIVE_DATA_DIR = "/../../../public_html/dir/dir/";

  function __construct()
  {
    echo "YAAAY! " . __METHOD__ . " success \n"; 
    return true;
  }

  public static function getSectors(){
    $baseUrl=self::BASE_URL.self::TARGET_QUERY;
    $currentTime = date("Y-m-d-H-i-s");

    $permission = 0755;

    $indexData = array( "Overall" => array("sector_weight" => 1, "sector_coefficient" => 5,
    $sectorInfos=SectorController::iexSectorParams();
    foreach ($sectorInfos as $a => $sectorInfo) {
      $sectorUrl = $baseUrl . implode(",", array_keys($sectorInfo["selected_tickers"])) . "&types=quote&range=1m";
      $rawSectorJson = file_get_contents($sectorUrl);
      $rawSectorArray = json_decode($rawSectorJson, true);

      // Write the raw file
      $rawSectorDir =  __DIR__ . self::EACH_SECTOR_DIR_PREFIX . $sectorInfo["directory"];

      if (!is_dir($rawSectorDir)) {
        mkdir($rawSectorDir, $permission, true);
      }

      $rawSectorFile = $rawSectorDir . "/" . $currentTime . ".json";
      $fp = fopen($rawSectorFile, "a+");
      fwrite($fp, $rawSectorJson);
      fclose($fp);

      // Calculate the real-time index
      $indexValue = 0;
      foreach ($rawSectorArray as $ticker => $tickerStats) {
        if (isset($sectorInfo["selected_tickers"][$ticker], $tickerStats["quote"], $tickerStats["quote"]["extendedChangePercent"], $tickerStats["quote"]["changePercent"], $tickerStats["quote"]["ytdChange"])) {

          $changeAmount = ($tickerStats["quote"]["extendedChangePercent"] + $tickerStats["quote"]["changePercent"] + $tickerStats["quote"]["ytdChange"])/200;
          $indexValue += $sectorInfo["sector_weight"] * $sectorInfo["selected_tickers"][$ticker] * $changeAmount;
        }
      }

      $indexData[$sectorInfo["sector"]] = array("sector_weight" => $sectorInfo["sector_weight"], "sector_coefficient" => 5,
      $indexData["Overall"]["sector_value"] += $indexData[$sectorInfo["sector"]]["sector_value"];
    }

    // Calculate the index factor for better visibility between -1 and +1
    $frontIndexData = array();
    foreach ($indexData as $sectorName => $sectorIndexData) {
      $indexSign = $sectorIndexData["sector_value"];
      if ($indexSign < 0) {
        $indexSign = - $indexSign;
      }

      $indexFactor = 1;
      for ($i=0; $i <= 10; $i++) { 
        $indexFactor = pow(10, $i);
        if (($indexFactor * $indexSign) > 1) {
          $indexFactor = pow(10, $i - 1);
          break;
        }
      }

      $frontIndexData[$sectorName] = $sectorIndexData["sector_weight"] * $sectorIndexData["sector_coefficient"] * $sectorIndexData["sector_value"] * $indexFactor;
    }

    // Write the index file
    $indexSectorDir =  __DIR__ . self::INDEX_SECTOR_DIR_PREFIX;

    if (!is_dir($indexSectorDir)) {mkdir($indexSectorDir, $permission, true);}

    $indexSectorFile = $indexSectorDir . $currentTime . ".json";

    $indexSectorJson = json_encode($frontIndexData, JSON_FORCE_OBJECT);
    $fp = fopen($indexSectorFile, "a+");
    fwrite($fp, $indexSectorJson);
    fclose($fp);

    $sectorDir =  __DIR__ . self::LIVE_DATA_DIR;


    if (!is_dir($sectorDir)) {mkdir($sectorDir, $permission, true);} // if data directory did not exist

    // if text file did not exist
    if (!file_exists($sectorDir . "text.txt")){
      $handle=fopen($sectorDir . "text.txt", "wb");
      fwrite($handle, "d");
      fclose($handle);
    }

    $sectorCoefFile = $sectorDir . "text.txt";
    copy($indexSectorFile, $sectorCoefFile);
    echo "YAAAY! " . __METHOD__ . " updated sector coefficients successfully !\n";

    return $frontIndexData;
  }


  public static function iexSectorParams(){
    $sectorInfos = array(
      array(
        "sector" => "IT",
        "directory" => "information-technology",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array( 
          "AAPL" => 0.05,
          "AMZN" => 0.05,
          "GOOGL" => 0.05,
          "IBM" => 0.05,
          "MSFT" => 0.05,
        )
      ),
      array( 
        "sector" => "Telecommunication",
        "directory" => "telecommunication-services",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array(
          "VZ" => 0.05,
          "CSCO" => 0.05,
          "CMCSA" => 0.05,
          "T" => 0.05,
          "CTL" => 0.05,
        )
      ),
      array( 
        "sector" => "Finance",
        "directory" => "financial-services",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array( 
          "JPM" => 0.05,
          "GS" => 0.05,
          "V" => 0.05,
          "BAC" => 0.05,
          "AXP" => 0.05,
        )
      ),
      array(
        "sector" => "Energy",
        "directory" => "energy",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array(
          "CVX" => 0.05,
          "XOM" => 0.05,
          "APA" => 0.05,
          "COP" => 0.05,
        )
      ),
      array(
        "sector" => "Industrials",
        "directory" => "industrials",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array(
          "CAT" => 0.05,
          "FLR" => 0.05,
          "GE" => 0.05,
          "JEC" => 0.05,
        )
      ),
      array(
        "sector" => "Materials and Chemicals",
        "directory" => "materials-and-chemicals",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array(
          "DWDP" => 0.05,
          "APD" => 0.05,
          "EMN" => 0.05,
          "ECL" => 0.05,
          "FMC" => 0.05,
        )
      ),
      array(
        "sector" => "Utilities",
        "directory" => "utilities",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array(
          "PPL" => 0.05,
          "PCG" => 0.05,
          "SO" => 0.05,
          "WEC" => 0.05,
        )
      ),
      array( 
        "sector" => "Consumer Discretionary",
        "directory" => "consumer-discretionary",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array(
          "DIS" => 0.05,
          "HD" => 0.05,
          "BBY" => 0.05,
          "CBS" => 0.05,
          "CMG" => 0.05,
        )
      ),
      array(
        "sector" => "Consumer Staples",
        "directory" => "consumer-staples",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array( 
          "PEP" => 0.05,
          "PM" => 0.05,
          "PG" => 0.05,
          "MNST" => 0.05,
          "TSN" => 0.05,
        )
      ),
      array( 
        "sector" => "Defense",
        "directory" => "defense-and-aerospace",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array( 
          "BA" => 0.05,
          "LMT" => 0.05,
          "UTX" => 0.05,
          "NOC" => 0.05,
          "HON" => 0.05,
        )
      ),
      array( 
        "sector" => "Health",
        "directory" => "health-care-and-pharmaceuticals",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array( 
          "UNH" => 0.05,
          "JNJ" => 0.05,
          "PFE" => 0.05,
          "UHS" => 0.05,
          "AET" => 0.05,
          "RMD" => 0.05,
        )
      ),


      array(
        "sector" => "Real Estate",
        "directory" => "real-estate",
        "sector_weight" => 0.05,
        "sector_coefficient" => 5,
        "selected_tickers" => array(
          "CCI" => 0.05,
          "AMT" => 0.05,
          "AVB" => 0.05,
          "HCP" => 0.05,
          "RCL" => 0.05,
          "HST" => 0.05,
        )
      )
    );
    return $sectorInfos;
  }


  function __destruct()
  {
    echo "YAAAY! " . __METHOD__ . " success!  \n";
    return true;
  }

}

输出(text.txt)

{“总体”:0.05,"IT":0.05,“电信”:0.05,“金融”:0.05,“能源”:0.05,“工业”:0.05,“材料和化学品”:0.05,“公用事业”:0.05,“消费者酌处”:0.05,“消费者自由裁量”:0.05,“国防”:0.05,“健康”:0.05,“房地产”:0.05}

EN

回答 1

Code Review用户

回答已采纳

发布于 2019-03-18 12:23:02

我不完全理解你的脚本在做什么,但我可以提供一些改进。

  1. 关于$sectorUrl = $baseUrl . implode(",", array_keys($sectorInfo["selected_tickers"])) . "&types=quote&range=1m";,因为您正在构建一个url,所以我认为使用%2C进行内爆以使RFC人员高兴是更好的做法。
  2. 在json字符串后面添加json字符串看起来不是个好主意。由于这个原因,您不应该使用a+编写。如果要将json数据合并到单个json文件上,则需要提取、解码、与下一个数据合并,然后在更新文件之前重新编码。否则,您将在.json文件中生成无效的json。
  3. 与其用if ($indexSign < 0) {$indexSign = - $indexSign;}手动将负值转换为正值,不如使用abs()强制值为正。$indexSign = abs($sectorIndexData);
  4. 可以在不迭代数学的情况下确定$indexFactor,您可以将它看作一个字符串,并将零数到小数点的右边。$indexFactor = 10 ** strlen(preg_match(‘.\k0+’,$float,$zeros)?$zeros : 0)模式中的\K意味着“重新启动完全字符串匹配”,在这种情况下,说“忘记以前匹配的字符(点)”可能会更清楚一些。pow()可以编写为来自php5.6+的**

除了这几篇,我看不出有什么可评论的。正如我在最近关于您的问题的文章中所指出的,始终尽量减少fwrite()调用的总数。

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/215541

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档