Visualizing Stock Data and Building K‑Line Charts with Python
This guide walks you through importing stock data, cleaning column names, visualizing price and volume trends, creating candlestick (K‑line) charts, analyzing relative changes, exploring correlations, and implementing a simple moving‑average trading strategy using pandas, matplotlib, and numpy.
Data Import and Cleaning
Stock data is stored in stockData.txt. It is read into a pandas DataFrame with
pd.read_table('stockData.txt', usecols=range(15), parse_dates=[0], index_col=0). The column name ' open' contains leading spaces and is renamed to 'open' using stock.rename(columns={' open':'open'}, inplace=True). The first five rows are displayed with stock.head() and the DataFrame information is inspected via stock.info().
Data Observation
The dataset includes price‑related indicators (open, close, high, low, price_change, ma5, ma10, ma20) and volume‑related indicators (volume, turnover, v_ma5, v_ma10, v_ma20). A table image illustrates these metrics.
Time Series Plot
The closing price is plotted over time with stock['close'].plot(grid=True), producing a line chart that shows price fluctuations.
K‑Line (Candlestick) Chart
Matplotlib’s candlestick_ohlc function from the matplotlib.finance module is used to draw a candlestick chart. A helper function pandas_candlestick_ohlc(stock_data, otherseries=None) sets up the figure, formats the date axis, and calls candlestick_ohlc with appropriate colors. The resulting chart shows daily open, high, low, and close prices, where red indicates an up day and green a down day.
Relative Change
Relative price change is calculated by dividing the closing price by the initial price: stock['return'] = stock['close'] / stock['close'].iloc[0]. The return series is plotted with a zero reference line.
Correlation Analysis
A subset of columns ( close, price_change, ma20, volume, v_ma20, turnover) is selected and visualized with pd.scatter_matrix to examine pairwise relationships. A correlation matrix is computed with np.corrcoef(small.T) and displayed using plt.matshow. The matrix reveals a strong positive correlation (≈0.91) between closing price and volume.
Dual‑Axis Plot of Close and Volume
The closing price and volume are plotted together with separate y‑axes using
stock[['close','volume']].plot(secondary_y='volume', grid=True).
Moving Average Strategy
Google stock data is fetched from Yahoo using pandas_datareader. After renaming columns to lowercase, 5‑day and 20‑day moving averages are computed with
stock['ma5'] = np.round(stock['close'].rolling(window=5, center=False).mean(), 2)and
stock['ma20'] = np.round(stock['close'].rolling(window=20, center=False).mean(), 2). The difference stock['ma5-20'] = stock['ma5'] - stock['ma20'] is signed and plotted to identify crossover points. A signal series is derived by taking the sign of the difference’s first derivative:
stock['signal'] = np.sign(stock['diff'] - stock['diff'].shift(1)). Buy signals (1) and sell signals (‑1) are plotted.
Back‑Testing the Strategy
Buy and sell dates are extracted from the signal series and combined into a trade DataFrame that records the operation (Buy/Sell) and the closing price on that day. Sorting the trades shows two complete cycles, but both sell prices are lower than the corresponding buy prices, resulting in a loss. The tutorial notes that this simple moving‑average crossover is only illustrative and not a guaranteed profitable strategy.
The article concludes that while the moving‑average crossover can be useful over longer time horizons, real‑world trading requires more sophisticated risk management and portfolio allocation.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
