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 code iterates through the gold data, starting from the third data point. It checks whether three consecutive closing prices are greater than the values in the trend line. If the condition is met, it calculates a new regression line from that point and updates the 'Trend' column. The new regression line is added to the store list for later display on the chart.



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.



 This results in a new line that can serve as support and resistance. What do you think of this approach?

Komentarze

Popularne posty z tego bloga

Join Me on a Journey to Master Python and Machine Learning for Data Analysis and Trading

Exploring Pearson Correlation in the World of Finance: A Deeper Understanding