I am using php 7 and I get portfolio data via json.
I want to sum up the portfolio and created the following google sheet:
The final result is shown in yellow. Basically, if a stock symbol is from asset_type
stock
and then sum up or deduct from the symbol value.
Find here the spreadsheet.
I tried the following:
<?php
$data = json_decode('[{"owner":"Self","transaction_date":"2020-03-10","asset_type":"stock","trx_type":"sale (partial)","amount_range":"$15,001 - $50,000","symbol":"VWO","name":"Vanguard FTSE Emerging Markets Index Fund ETF Shar"},
{"owner":"Self","transaction_date":"2020-03-10","asset_type":"stock","trx_type":"sale (partial)","amount_range":"$15,001 - $50,000","symbol":"GOOG","name":"Alphabet Inc."},
{"owner":"Self","transaction_date":"2020-03-10","asset_type":"stock","trx_type":"sale (full)","amount_range":"$15,001 - $50,000","symbol":"VWO","name":"Vanguard FTSE Emerging Markets Index Fund ETF Shar"},
{"owner":"Self","transaction_date":"2020-03-10","asset_type":"stock","trx_type":"sale (partial)","amount_range":"$1,001 - $15,000","symbol":"GOOG","name":"Alphabet Inc."},
{"owner":"Self","transaction_date":"2020-03-10","asset_type":"stock","trx_type":"sale (full)","amount_range":"$1,001 - $15,000","symbol":"VWO","name":"Vanguard FTSE Emerging Markets Index Fund ETF Shar"},
{"owner":"Self","transaction_date":"2020-03-10","asset_type":"stock","trx_type":"purchase","amount_range":"$1,001 - $15,000","symbol":"GOOG","name":"Alphabet Inc."},
{"owner":"Self","transaction_date":"2020-03-10","asset_type":"municipal security","trx_type":"purchase","amount_range":"$1,001 - $15,000","symbol":"GOOG","name":"Alphabet Inc."},
{"owner":"Self","transaction_date":"2020-03-10","asset_type":"stock","trx_type":"purchase","amount_range":"$100,000 - $150,000","symbol":"AAPL","name":"Apple Inc."}]');
$portfolio = 0;
$res = [];
foreach ($data as $d1) {
if ($d1->asset_type === "stock" && !in_array_r($d1->symbol, $res)) { //check if value exists in array
foreach ($data as $d2) {
if ($d2->asset_type === "stock" && $d1->symbol === $d2->symbol) {
$a = array_map('intval', explode(" - ", str_replace(",", "", str_replace("$", "", $d2->amount_range))));
$avg = array_sum($a) / count($a);
// string contains - https://stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word
if (strpos($d2->trx_type, "sale") !== false) {
$portfolio -= $avg;
}
if (strpos($d2->trx_type, "purchase") !== false) {
$portfolio += $avg;
}
}
}
if ($portfolio > 0) {
array_push($res, [$d1, $portfolio]);
}
}
}
echo $res;
/**
* Check an array if an item exists
* @param $item
* @param $array
* @return false|int
*/
function in_array_r($item, $array)
{
return preg_match('/"' . preg_quote($item, '/') . '"/i', json_encode($array));
}
I get an empty $res
array after running this code.
Any suggestions what I am doing wrong?
I appreciate your replies!