How to Build a Python Stock Temperature Analyzer with Tushare
This tutorial shows how to fetch ten years of stock fundamentals using Tushare, compute a probabilistic "temperature" metric with NumPy and SciPy, and visualize the temperature alongside closing prices in Matplotlib, providing a complete end‑to‑end Python data‑analysis workflow.
1. Get Data
Import the tushare package, set your token, and call the daily_basic interface to retrieve daily fundamental indicators (PE, PB, etc.) for a given stock over a ten‑year period.
# import package
import tushare as ts
# token (obtain from https://tushare.pro/register)
ts_token = 'YOUR_TOKEN'
pro = ts.pro_api(ts_token)
# date range
import datetime
days = 365 * 10
end_date = datetime.date.today().strftime('%Y%m%d')
start_date = (datetime.date.today() - datetime.timedelta(days=days)).strftime('%Y%m%d')
# fetch data
stock_data = pro.daily_basic(ts_code='000001.SZ',
start_date=start_date,
end_date=end_date,
fields='ts_code,trade_date,close,turnover_rate,volume_ratio,pe,pb,total_mv')2. Process Data
Use numpy to compute rolling means and standard deviations of pe and pb, then apply the normal cumulative distribution function from scipy.stats to obtain a “temperature” value (scaled to 0‑100) for each day.
# import packages
import numpy as np
import scipy.stats as st
# initialise temperature columns
stock_data['pe_temperature'] = 0.5
stock_data['pb_temperature'] = 0.5
for i in range(1, len(stock_data)):
# PE
mean = np.mean(stock_data['pe'][:i+1])
std = np.std(stock_data['pe'][:i+1], ddof=1)
stock_data['pe_temperature'].iloc[i] = st.norm.cdf(stock_data['pe'].iloc[i], loc=mean, scale=std)
# PB
mean = np.mean(stock_data['pb'][:i+1])
std = np.std(stock_data['pb'][:i+1], ddof=1)
stock_data['pb_temperature'].iloc[i] = st.norm.cdf(stock_data['pb'].iloc[i], loc=mean, scale=std)
# combine into a single temperature
stock_data['temperature'] = (stock_data['pe_temperature'] + stock_data['pb_temperature']) * 503. Visualise Results
Sort the data by trade date and plot the temperature together with the closing price using matplotlib. The left y‑axis shows the temperature, the right y‑axis shows the closing price.
# import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
stock_data.sort_values(by='trade_date', ascending=True, inplace=True)
fig, ax1 = plt.subplots()
ax1.set_title('stock temperature')
ax1.set_xlabel('time')
ax1.set_ylabel('temperature')
ax2 = ax1.twinx()
ax2.set_ylabel('close')
data_len = stock_data.shape[0]
locator = MultipleLocator(data_len/10)
ax1.xaxis.set_major_locator(locator)
ax2.xaxis.set_major_locator(locator)
ax1.plot(stock_data['trade_date'], stock_data['temperature'],
linestyle='--', marker='.', alpha=0.5, color='r', label='temperature')
ax2.plot(stock_data['trade_date'], stock_data['close'],
linestyle='-', marker='.', color='g', label='close')
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.show()The resulting chart displays the stock’s temperature curve alongside its closing price over time.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
