Implementing Common Technical Analysis Methods to Identify Market Trends Using Akshare, Pandas, and TA Libraries

·

Technical analysis is a cornerstone for traders and investors aiming to assess financial market trends and make informed decisions. By leveraging historical price and volume data, technical indicators help reveal patterns, momentum shifts, and potential reversal points in asset prices. In this guide, we’ll explore how to implement six widely used technical analysis methods using Python, specifically with the akshare, pandas, and ta libraries.

We'll use Kweichow Moutai (stock code: 600519) as our case study, analyzing its price performance from the beginning of 2024 through October 18, 2024. This real-world example will demonstrate how Python can be used to automate technical signal generation and support data-driven trading strategies.


Core Keywords

These keywords reflect both the tools and the intent behind this analysis—helping traders and developers build robust systems for market evaluation.


Setting Up the Environment

Before diving into strategy implementation, ensure you have the required libraries installed:

pip install akshare pandas ta matplotlib

Now, import the necessary modules and fetch historical stock data using akshare, a powerful open-source financial data toolkit for Chinese markets:

import akshare as ak
import pandas as pd
import matplotlib.pyplot as plt
from ta.trend import SMAIndicator
from ta.momentum import MACD

# Configure plot settings for Chinese font display (Mac: STHeiti, Windows: SimHei)
plt.rcParams["font.sans-serif"] = ["STHeiti"]
plt.rcParams["axes.unicode_minus"] = False

# Define parameters
stock_code = "600519"
start_date = "20240101"
end_date = "20241018"

# Fetch adjusted historical data
df = ak.stock_zh_a_hist(symbol=stock_code, start_date=start_date, end_date=end_date, adjust="qfq")
df['日期'] = pd.to_datetime(df['日期'])
df.set_index('日期', inplace=True)

This code retrieves fully adjusted price data for Kweichow Moutai, ensuring accuracy in backtesting by accounting for dividends and stock splits.

👉 Discover how professional traders automate market signals using real-time data tools.


1. Fast and Slow Moving Averages (SMA Crossover)

One of the most intuitive trend-following strategies is the moving average crossover. It uses two simple moving averages (SMAs): a fast one (e.g., 20-day) and a slow one (e.g., 50-day).

Implementation:

df['SMA20'] = SMAIndicator(close=df['收盘'], window=20).sma_indicator()
df['SMA50'] = SMAIndicator(close=df['收盘'], window=50).sma_indicator()

# Generate trading signals
df['Signal'] = 0
df.loc[df['SMA20'] > df['SMA50'], 'Signal'] = 1
df.loc[df['SMA20'] < df['SMA50'], 'Signal'] = -1

# Plot results
plt.figure(figsize=(12, 6))
plt.plot(df.index, df['收盘'], label='Closing Price', linewidth=1.5)
plt.plot(df.index, df['SMA20'], label='20-Day SMA', alpha=0.7)
plt.plot(df.index, df['SMA50'], label='50-Day SMA', alpha=0.7)
plt.title('Kweichow Moutai – SMA Crossover Strategy')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

The visualization clearly shows periods where the short-term average confirms bullish or bearish momentum shifts.


2. Combining Moving Averages with MACD

To improve signal reliability, combine trend-following indicators like SMAs with momentum oscillators such as the Moving Average Convergence Divergence (MACD).

The MACD consists of:

Enhanced strategy logic:

Implementation:

macd = MACD(close=df['收盘'])
df['MACD'] = macd.macd()
df['MACD_Signal'] = macd.macd_signal()
df['MACD_Hist'] = macd.macd_diff()

# Combined signal: Uptrend + Bullish MACD crossover
df['Combined_Signal'] = 0
buy_condition = (df['收盘'] > df['SMA50']) & (df['MACD'] > df['MACD_Signal'])
df.loc[buy_condition, 'Combined_Signal'] = 1

This dual-filter approach reduces noise and aligns trades with broader market trends.

👉 Learn how advanced traders integrate multiple indicators to refine entry and exit timing.


Frequently Asked Questions (FAQ)

Q: What makes technical analysis effective for stock trading?
A: Technical analysis works because market behavior often repeats due to investor psychology. Patterns in price and volume reflect supply and demand dynamics, allowing traders to anticipate future movements based on historical trends.

Q: Can these strategies be applied to other assets like cryptocurrencies or forex?
A: Absolutely. While this example uses Chinese equities, the same methods apply to crypto, forex, commodities, and ETFs—any asset with time-series pricing data.

Q: Is Python suitable for real-time trading systems?
A: Yes. With proper architecture (e.g., event-driven engines, low-latency data feeds), Python can power live trading bots. Libraries like akshare, ccxt, or alpaca-trade-api enable integration with exchanges.

Q: How do I avoid overfitting my technical strategies?
A: Always test on out-of-sample data, use walk-forward analysis, and keep models simple. Avoid optimizing parameters too tightly to past data.

Q: Are moving averages lagging indicators? How does that affect performance?
A: Yes, SMAs are lagging—they rely on past prices. This delay means they work best in trending markets but may underperform in choppy conditions. Pairing them with momentum filters (like RSI or MACD) helps mitigate lags.


Expanding to Other Indicators

Beyond SMAs and MACD, the ta library supports numerous indicators:

Each adds a new dimension to your analysis framework.


Final Thoughts

By combining akshare for data retrieval, pandas for data manipulation, and ta for indicator computation, you can build a powerful technical analysis pipeline entirely in Python. Whether you're scanning for trends, generating trade signals, or visualizing market behavior, automation enhances consistency and removes emotional bias.

These techniques are not limited to individual stocks—they scale across portfolios, timeframes, and asset classes. As you refine your models, consider integrating risk management rules and position sizing algorithms for a complete trading system.

👉 Start building your own algorithmic trading strategies with powerful data analytics tools today.