T

50
python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Define the moving averages parameters
short_ma_period = 10 # Shorter moving average period
long_ma_period = 30 # Longer moving average period

# Generate random price data (replace with your own data)
price_data = np.random.randint(low=90, high=110, size=100)

# Create a DataFrame with the price data
df = pd.DataFrame({'Price': price_data})

# Calculate the moving averages
df['Short MA'] = df['Price'].rolling(window=short_ma_period).mean()
df['Long MA'] = df['Price'].rolling(window=long_ma_period).mean()

# Generate buy and sell signals
df['Signal'] = np.where(df['Short MA'] > df['Long MA'], 1, -1)

# Generate the chart
plt.plot(df['Price'], label='Price')
plt.plot(df['Short MA'], label=f'Short MA ({short_ma_period})')
plt.plot(df['Long MA'], label=f'Long MA ({long_ma_period})')
plt.plot(df.loc[df['Signal'] == 1, 'Price'], 'go', label='Buy Signal')
plt.plot(df.loc[df['Signal'] == -1, 'Price'], 'ro', label='Sell Signal')
plt.legend()
plt.title('Moving Average Trading Strategy')
plt.xlabel('Time')
plt.ylabel('Price')
plt.show()

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.