The exchange provides real-time market data including open/high/low/close prices and trading volumes via its official API endpoints. This structured data is crucial for market participants analyzing price trends and making investment decisions.
Data Acquisition Process
- Identify the target API endpoint for historical price data
- Construct POST requests with appropriate authentication headers
- Parse and store the returned JSON data in CSV format
Key Request Components
- Headers: Include User-Agent and Referer fields for request validation
- Payload: Contract identifier (e.g., 'Au99.99') as form data
- Response: Structured JSON containing price records
Python Implementation
import requests
import csv
from datetime import datetime
# Configuration parameters
contract_id = "Au99.99"
output_file = f"SGE_{contract_id.replace('(', '_').replace(')', '_')}_{datetime.now().strftime('%Y%m%d')}.csv"
# API request setup
url = "https://www.sge.com.cn/graph/Dailyhq"
headers = {
'User-Agent': 'Mozilla/5.0',
'Referer': 'https://www.sge.com.cn/',
'X-Requested-With': 'XMLHttpRequest'
}
payload = {'instid': contract_id}
# Data retrieval and storage
try:
response = requests.post(url, headers=headers, data=payload, timeout=10)
response.raise_for_status()
price_data = response.json()
with open(output_file, 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.writer(f)
writer.writerow(['Date', 'Open', 'High', 'Low', 'Close'])
writer.writerows(price_data['data'])
print(f"Saved {len(price_data['data'])} records to {output_file}")
except Exception as e:
print(f"Request failed: {e}")
Data Visualization
The following implementation uses ECharts to create an interactive HTML visualization of gold price trends:
import pandas as pd
import os
# Load and prepare data
file_path = 'SGE_Au99.99_20250818.csv'
price_df = pd.read_csv(file_path)
price_df['Date'] = pd.to_datetime(price_df['Date']).dt.strftime('%Y-%m-%d')
price_df.sort_values('Date', inplace=True)
# Generate HTML visualization
html_content = f"""
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/echarts"></script>
<style>.container {{ width: 90%; max-width: 1200px; margin: auto; }}</style>
</head>
<body>
<div class="container">
<h2>Au99.99 Price Trend ({price_df['Date'].iloc[0]} - {price_df['Date'].iloc[-1]})</h2>
<div id="chart" style="height:500px;"></div>
</div>
<script>
const chart = echarts.init(document.getElementById('chart'));
chart.setOption({{
tooltip: {{ trigger: 'axis' }},
xAxis: {{ type: 'category', data: {json.dumps(price_df['Date'].tolist())} }},
yAxis: {{ type: 'value' }},
series: [{{
name: 'Closing Price',
type: 'line',
data: {json.dumps(price_df['Close'].round(2).tolist())},
smooth: true,
itemStyle: {{ color: '#4a86e8' }}
}}]
}});
</script>
</body>
</html>
"""
with open("gold_price_trend.html", "w", encoding="utf-8") as f:
f.write(html_content)
Historical Price Anaylsis (2016-2025)
- Long-term upward trend with 150% price increase
- Key drivers include global economic uncertainty, monetary policy shifts, and geopolitical factors
- Distinct market phases observed:
- 2016-2017: Stable base (~300 RMB/g)
- 2018-2019: Gradual ascent to 400 RMB/g
- 2020-2023: Volatile consolidation between 400-500 RMB/g
- 2023-2025: Sharp rise to 800 RMB/g peak
This analysis demonstrates the effectiveness of programmatic data collection and visualization for tracking precious metal price dynamics.