time(), 'data' => $data ]; return saveCache($cache); } function getCacheStatus() { global $CACHE_FILE; $status = [ 'file_path' => $CACHE_FILE, 'exists' => file_exists($CACHE_FILE), 'readable' => is_readable($CACHE_FILE), 'directory_writable' => is_writable(dirname($CACHE_FILE)), 'file_writable' => file_exists($CACHE_FILE) ? is_writable($CACHE_FILE) : null ]; return $status; } // ============================================================ // PARSE CLIPBOARD DATA IF PROVIDED // ============================================================ function parseClipboardData($jsonData, &$rawResponse = null) { $result = [ 'market_cap' => null, 'trailing_pe' => null, 'forward_pe' => null, 'peg_ratio' => null, 'price_to_sales' => null, 'price_to_book' => null, 'ev_to_revenue' => null, 'ev_to_ebitda' => null, 'profit_margin' => null, 'quarterly_revenue_growth' => null, 'available' => false ]; $data = json_decode($jsonData, true); $rawResponse = $jsonData; if (!$data || !isset($data['Symbol'])) { return $result; } $result['market_cap'] = isset($data['MarketCapitalization']) ? floatval($data['MarketCapitalization']) : null; $result['trailing_pe'] = isset($data['TrailingPE']) ? floatval($data['TrailingPE']) : null; $result['forward_pe'] = isset($data['ForwardPE']) ? floatval($data['ForwardPE']) : null; $result['peg_ratio'] = isset($data['PEGRatio']) ? floatval($data['PEGRatio']) : null; $result['price_to_sales'] = isset($data['PriceToSalesRatioTTM']) ? floatval($data['PriceToSalesRatioTTM']) : null; $result['price_to_book'] = isset($data['PriceToBookRatio']) ? floatval($data['PriceToBookRatio']) : null; $result['ev_to_revenue'] = isset($data['EVToRevenue']) ? floatval($data['EVToRevenue']) : null; $result['ev_to_ebitda'] = isset($data['EVToEBITDA']) ? floatval($data['EVToEBITDA']) : null; $result['profit_margin'] = isset($data['ProfitMargin']) ? floatval($data['ProfitMargin']) * 100 : null; $result['quarterly_revenue_growth'] = isset($data['QuarterlyRevenueGrowthYOY']) ? floatval($data['QuarterlyRevenueGrowthYOY']) * 100 : null; $result['available'] = true; return $result; } // ============================================================ // FETCH FUNDAMENTAL DATA FROM ALPHA VANTAGE (WITH CACHE) // ============================================================ function getAlphaVantageFundamentals($symbol, $apiKey, $forceRefresh = false) { $result = [ 'market_cap' => null, 'trailing_pe' => null, 'forward_pe' => null, 'peg_ratio' => null, 'price_to_sales' => null, 'price_to_book' => null, 'ev_to_revenue' => null, 'ev_to_ebitda' => null, 'profit_margin' => null, 'quarterly_revenue_growth' => null, 'available' => false, 'rate_limited' => false, 'raw_response' => null ]; // Check cache first (unless force refresh) if (!$forceRefresh) { $cached = getCachedData($symbol); if ($cached) { $cached['from_cache'] = true; return $cached; } } $url = "https://www.alphavantage.co/query?function=OVERVIEW&symbol={$symbol}&apikey={$apiKey}"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'); curl_setopt($ch, CURLOPT_TIMEOUT, 15); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Accept: application/json', 'Accept-Language: en-US,en;q=0.9', ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $result['raw_response'] = $response; if (!$response || $httpCode !== 200) { return $result; } $data = json_decode($response, true); if (isset($data['Note']) && strpos($data['Note'], 'API rate limit') !== false) { $result['rate_limited'] = true; $result['raw_response'] = $response; return $result; } if (empty($data) || isset($data['Error Message']) || !isset($data['Symbol'])) { return $result; } $result['market_cap'] = isset($data['MarketCapitalization']) ? floatval($data['MarketCapitalization']) : null; $result['trailing_pe'] = isset($data['TrailingPE']) ? floatval($data['TrailingPE']) : null; $result['forward_pe'] = isset($data['ForwardPE']) ? floatval($data['ForwardPE']) : null; $result['peg_ratio'] = isset($data['PEGRatio']) ? floatval($data['PEGRatio']) : null; $result['price_to_sales'] = isset($data['PriceToSalesRatioTTM']) ? floatval($data['PriceToSalesRatioTTM']) : null; $result['price_to_book'] = isset($data['PriceToBookRatio']) ? floatval($data['PriceToBookRatio']) : null; $result['ev_to_revenue'] = isset($data['EVToRevenue']) ? floatval($data['EVToRevenue']) : null; $result['ev_to_ebitda'] = isset($data['EVToEBITDA']) ? floatval($data['EVToEBITDA']) : null; $result['profit_margin'] = isset($data['ProfitMargin']) ? floatval($data['ProfitMargin']) * 100 : null; $result['quarterly_revenue_growth'] = isset($data['QuarterlyRevenueGrowthYOY']) ? floatval($data['QuarterlyRevenueGrowthYOY']) * 100 : null; $result['available'] = true; $result['from_cache'] = false; // Save to cache saveToCache($symbol, $result); return $result; } // ============================================================ // FETCH CHART DATA FROM YAHOO FINANCE // ============================================================ $url = "https://query1.finance.yahoo.com/v8/finance/chart/{$symbol}?interval=1d&range=6mo"; $response = @file_get_contents($url); if ($response === false) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($ch); curl_close($ch); } if (!$response) { die("❌ Could not fetch chart data for {$symbol}"); } $data = json_decode($response, true); $result = $data['chart']['result'][0] ?? null; if (!$result) { die("❌ Invalid response for {$symbol}"); } // Parse chart data $meta = $result['meta']; $currentPrice = $meta['regularMarketPrice'] ?? 0; $currency = $meta['currency'] ?? 'USD'; $fiftyTwoWeekHigh = $meta['fiftyTwoWeekHigh'] ?? 0; $fiftyTwoWeekLow = $meta['fiftyTwoWeekLow'] ?? 0; $longName = $meta['longName'] ?? $symbol; $timestamp = $result['timestamp'] ?? []; $quote = $result['indicators']['quote'][0] ?? []; $closes = $quote['close'] ?? []; // Filter valid prices $prices = []; $dates = []; for ($i = 0; $i < count($timestamp); $i++) { if (isset($closes[$i]) && $closes[$i] !== null && $closes[$i] > 0) { $prices[] = $closes[$i]; $dates[] = date('M d', $timestamp[$i]); } } if (count($prices) < 10) { die("❌ Not enough price data for {$symbol}"); } // Calculate returns $oldPrice = $prices[0]; $newPrice = end($prices); $totalReturn = (($newPrice - $oldPrice) / $oldPrice) * 100; // Acceleration test: last 30 vs previous 30 days $recent = array_slice($prices, -30); $previous = array_slice($prices, -60, 30); $recentReturn = 0; $previousReturn = 0; if (count($recent) >= 2) { $recentReturn = (($recent[count($recent)-1] - $recent[0]) / $recent[0]) * 100; } if (count($previous) >= 2) { $previousReturn = (($previous[count($previous)-1] - $previous[0]) / $previous[0]) * 100; } $isAccelerating = $recentReturn > $previousReturn; $isAccelerator = ($totalReturn >= 50 && $isAccelerating); $totalReturnFormatted = round($totalReturn, 1); $recentReturnFormatted = round($recentReturn, 1); $previousReturnFormatted = round($previousReturn, 1); $fromHighPercent = $fiftyTwoWeekHigh > 0 ? round((($fiftyTwoWeekHigh - $currentPrice) / $fiftyTwoWeekHigh) * 100, 1) : 0; // ============================================================ // FETCH VALUATION METRICS - either from API, clipboard, or cache // ============================================================ $alphaRawResponse = null; if ($useClipboard) { $valuationMetrics = parseClipboardData($_POST['clipboard_data'], $alphaRawResponse); $dataSource = 'pasted'; // Save pasted data to cache! if ($valuationMetrics['available']) { $saveResult = saveToCache($symbol, $valuationMetrics); $valuationMetrics['cache_saved'] = $saveResult; $valuationMetrics['from_cache'] = false; } } else { $valuationMetrics = getAlphaVantageFundamentals($symbol, $ALPHA_VANTAGE_API_KEY, $forceRefresh); $alphaRawResponse = $valuationMetrics['raw_response'] ?? null; if (isset($valuationMetrics['from_cache']) && $valuationMetrics['from_cache']) { $dataSource = 'cache'; } else { $dataSource = 'api'; } } // Get cache status for display $cacheStatus = getCacheStatus(); // ============================================================ // EVALUATE THE 3 FORCES // ============================================================ $growthPass = ($totalReturn >= 50 && $isAccelerating); $financialPass = false; if ($valuationMetrics['available'] && $valuationMetrics['profit_margin'] !== null) { $financialPass = ($valuationMetrics['profit_margin'] > 0); } $valuationPass = false; $valuationSweetSpot = false; if ($valuationMetrics['available'] && $valuationMetrics['peg_ratio'] !== null && $valuationMetrics['peg_ratio'] > 0) { $valuationSweetSpot = ($valuationMetrics['peg_ratio'] < 1); $valuationPass = ($valuationMetrics['peg_ratio'] < 1.5); } $allThreeAlign = ($growthPass && $financialPass && $valuationPass); $isRateLimited = isset($valuationMetrics['rate_limited']) && $valuationMetrics['rate_limited']; $fromCache = isset($valuationMetrics['from_cache']) && $valuationMetrics['from_cache']; // ============================================================ // COMPACT MODE (UNCHANGED) // ============================================================ if ($isCompact) { $badge = $isAccelerator ? '🚀 Buy' : '× NOBUY'; $color = $isAccelerator ? '#10b981' : '#f59e0b'; $arrow = $totalReturn >= 0 ? '▲' : '▼'; $returnText = ($totalReturn >= 0 ? '+' : '') . $totalReturnFormatted . '%'; header('Content-Type: text/html; charset=utf-8'); ?>
"When all three align, that's the sweet spot for buying before the price rises."
💡 Tip: Copy the entire JSON from this link and paste above
$cachedData) {
$age = round((time() - $cachedData['timestamp']) / 3600, 1);
echo "\n{$cachedSymbol}: cached {$age} hours ago";
if (isset($cachedData['data']['peg_ratio'])) {
echo " (PEG: {$cachedData['data']['peg_ratio']})";
}
}
} else {
echo "Cache is empty";
}
echo "\n\n--- Files in directory ---\n";
$files = scandir(__DIR__);
foreach ($files as $file) {
if ($file != '.' && $file != '..' && $file != 'stock_rating.php') {
echo $file . "\n";
}
}
?>