I’m excited to share a project I recently worked on a Python script for generating candlestick charts with enhanced functionality. If you’re into stock analysis, this project is a practical and user-friendly way to visualize stock data.
I Built This Project
When analyzing stocks, I often needed a tool to visualize historical price movements with candlestick charts. While there are several platforms available, I wanted something customizable and interactive. That’s why I decided to build this script using Python with additional features like:
- Dynamic Date Input: To allow a flexible analysis range.
- Volume Display: Because volume is a crucial indicator in technical analysis.
- Chart Saving: To save charts locally for later review.
- Error Handling: To ensure smooth execution even with invalid inputs.
- Moving Averages: For identifying trends.
Prerequisites
Before we begin, you’ll need to install the required libraries. Open your terminal and run:
codepip install yfinance mplfinance
These libraries allow us to fetch stock data and plot candlestick charts.
The Code
Here’s the enhanced Python script:
codeimport yfinance as yf
import mplfinance as mpf
from datetime import datetime
def get_date_input(prompt):
"""Get a valid date input from the user."""
while True:
try:
date_input = input(prompt)
return datetime.strptime(date_input, "%Y-%m-%d").strftime('%Y-%m-%d')
except ValueError:
print("Invalid date format. Please use YYYY-MM-DD.")
def fetch_stock_data(symbol, start_date, end_date):
"""Fetch stock data from Yahoo Finance."""
try:
data = yf.download(symbol, start=start_date, end=end_date)
if data.empty:
raise ValueError(f"No data found for {symbol} in the given date range.")
return data
except Exception as e:
print(f"Error fetching data: {e}")
return None
def plot_candlestick_chart(stock_data, symbol, save_chart=False):
"""Plot and optionally save the candlestick chart."""
try:
mpf.plot(
stock_data,
type='candle',
style='yahoo',
title=f'{symbol.upper()} Candlestick Chart',
volume=True,
mav=(10, 20), # Add moving averages (10-day and 20-day)
savefig=f"{symbol}_candlestick_chart.png" if save_chart else None
)
if save_chart:
print(f"Candlestick chart saved as {symbol}_candlestick_chart.png")
except Exception as e:
print(f"Error plotting chart: {e}")
def main():
print("Welcome to the Candlestick Chart Plotter!")
print("Please provide the stock symbol and date range for the chart.")
symbol = input("Enter Stock Symbol (e.g., AAPL): ").upper()
start_date = get_date_input("Enter Start Date (YYYY-MM-DD): ")
end_date = get_date_input("Enter End Date (YYYY-MM-DD): ")
print(f"Fetching data for {symbol} from {start_date} to {end_date}...")
stock_data = fetch_stock_data(symbol, start_date, end_date)
if stock_data is not None:
save_option = input("Do you want to save the chart as an image? (y/n): ").lower()
save_chart = save_option == 'y'
plot_candlestick_chart(stock_data, symbol, save_chart)
else:
print("Unable to fetch stock data. Please try again with a valid stock symbol and date range.")
if __name__ == "__main__":
main()
Features Explained
- Dynamic Date Input:
- The
get_date_input
function validates user input to ensure the dates are in the correct format (YYYY-MM-DD
). - This allows flexibility for users to analyze specific time frames.
- The
- Fetching Stock Data:
- The
fetch_stock_data
function uses theyfinance
library to fetch historical stock data. - It includes error handling to manage invalid symbols or date ranges gracefully.
- The
- Candlestick Chart Plotting:
- The
plot_candlestick_chart
function generates a candlestick chart usingmplfinance
. - Features like volume bars and moving averages (10-day and 20-day) are added for better analysis.
- The
- Saving the Chart:
- Users can choose to save the chart as an image file (
.png
) for future reference.
- Users can choose to save the chart as an image file (
Running the Script
- Save the script as
candlestick_chart.py
. - Run the script in your Python environment:
the script in your Python environment:
codepython candlestick_chart.py
- Follow the prompts:
- Enter the stock symbol (e.g., AAPL for Apple Inc.).
- Specify the start and end dates.
- Decide if you want to save the chart.
Here’s an example of how it works:
codeWelcome to the Candlestick Chart Plotter!
Enter Stock Symbol (e.g., AAPL): TSLA
Enter Start Date (YYYY-MM-DD): 2022-01-01
Enter End Date (YYYY-MM-DD): 2023-01-01
Do you want to save the chart as an image? (y/n): y
Fetching data for TSLA from 2022-01-01 to 2023-01-01...
Candlestick chart saved as TSLA_candlestick_chart.png
Key Enhancements
Moving Averages
Moving averages help identify trends by smoothing out short-term price fluctuations. I’ve included 10-day and 20-day moving averages for quick trend analysis.
Volume Bars
Volume bars provide insights into trading activity and confirm price movements.
Error Handling
The script handles common errors, such as invalid stock symbols or empty datasets, making it more robust.
Applications
- Individual Investors: To analyze stock trends visually.
- Students: As a hands-on project to learn Python and data visualization.
- Traders: To save and share candlestick charts for further analysis.
Final Thoughts
I’ve found this project incredibly useful for my stock analysis. It’s also a great way to demonstrate Python’s versatility and the power of libraries like yfinance
and mplfinance
. Feel free to modify the code to suit your needs maybe add more indicators, or integrate it with a machine learning model for predictions.