Utilizing Linear Regression in Python for Effective Gold Trading Strategy
Today, I'd like to share with you a simple trading idea utilizing Python and linear regression. Let's start by importing the necessary libraries:
yfinance (yf): Used for fetching financial data, including
gold prices in this case.
pandas (pd): Used for data manipulation and storing data in
DataFrames.
numpy (np): Used for numerical calculations.
LinearRegression from sklearn: Used to create a linear
regression model.
mplfinance (mpf): Used for creating financial charts,
including candlestick charts.
I define the symbol for gold as 'GC=F'. The data for gold is
fetched from January 1, 2022, to January 11, 2024, with a daily interval
The calculate_new_regression function takes a DataFrame and
a starting index. It creates a new linear regression model using data from the
specified index to the end of the DataFrame. It returns the predicted trend
values, which are used as a new trend line.
I call the calculate_new_regression function for the entire
dataset, starting from index 0 (the beginning of the data). The result is
stored as a new 'Trend' column in the gold_data DataFrame. I create a list
named store, which holds objects to be added to the mplfinance chart.
Initially, it contains one trend line..
The style of the candlestick chart is defined. A candlestick
chart is drawn with the gold data, adding the regression lines from the store
list. The title and size of the chart are also set.
Komentarze
Prześlij komentarz