feat: 新增K线数据获取与分析示例脚本
添加 demo_kline_analysis.py 示例文件,展示如何使用 SDK 获取股票K线数据并进行基础分析(如计算平均价格)。该示例包含错误处理和数据格式化展示,便于开发者快速上手集成。
This commit is contained in:
1 parent
9d858d3553
commit
f336928c64
1 file changed
+53
@@ -0,0 +1,53 @@
|
||||
from itick import Client, Environment, KlinePeriod
|
||||
|
||||
from itick.exceptions import ITickError, AuthError
|
||||
|
||||
def main():
|
||||
try:
|
||||
# Initialize client
|
||||
client = Client(token="e66e496347e34d72a63cce71a4383c358b2c6d28d9d94bd48d2568cdc7b0f0da", environment=Environment.FREE)
|
||||
|
||||
# Get 1-minute Kline data for a stock (e.g., AAPL)
|
||||
print("Fetching 1-minute Kline data...")
|
||||
klines = client.stock.get_kline(
|
||||
region="US",
|
||||
code="AAPL",
|
||||
period=KlinePeriod.ONE_MINUTE.value,
|
||||
limit=10
|
||||
)
|
||||
|
||||
if not klines:
|
||||
print("No data found.")
|
||||
return
|
||||
|
||||
print(f"{'Time':<20} {'Open':<10} {'Close':<10} {'Volume':<15} {'Turnover':<15} {'Avg Price':<10}")
|
||||
print("-" * 85)
|
||||
|
||||
for k in klines:
|
||||
# Extract fields
|
||||
ts = k.get('t') # Timestamp
|
||||
open_p = k.get('o') # Open Price (Raw)
|
||||
close_p = k.get('c') # Close Price (Raw)
|
||||
vol = k.get('v') # Volume
|
||||
turnover = k.get('tu') # Turnover (Transaction Amount)
|
||||
|
||||
# Calculate Average Price (VWAP for this minute)
|
||||
# Avg Price = Turnover / Volume
|
||||
avg_price = turnover / vol if vol and vol > 0 else 0
|
||||
|
||||
# Convert timestamp to readable format (optional)
|
||||
import datetime
|
||||
dt = datetime.datetime.fromtimestamp(ts / 1000).strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
print(f"{dt:<20} {open_p:<10} {close_p:<10} {vol:<15} {turnover:<15} {avg_price:<10.2f}")
|
||||
|
||||
except AuthError as e:
|
||||
print(f"\nAuthentication Error: {e}")
|
||||
print("Please check if your token is valid and you have permissions for this endpoint.")
|
||||
except ITickError as e:
|
||||
print(f"\nSDK Error: {e}")
|
||||
except Exception as e:
|
||||
print(f"\nUnexpected Error: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user