Sample python code for intraday scalping
Intraday scalping is a trading strategy that involves making multiple trades within a day to take advantage of small price movements. Below is a sample Python code for a simple intraday scalping strategy using moving averages. This example will use the
yfinance
library to fetch historical stock data and the pandas
library for data manipulation. ### Required Libraries
Make sure you have the following libraries installed:
```bash
pip install yfinance pandas
```
### Sample Code for Intraday Scalping Strategy
```python
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def get_stock_data(ticker, period="1d", interval="1m"):
"""
Fetches historical stock data for the given ticker.
Args:
ticker (str): Stock ticker symbol.
period (str): Data period (default is '1d' for 1 day).
interval (str): Data interval (default is '1m' for 1 minute).
Returns:
pd.DataFrame: DataFrame containing stock data.
"""
stock = yf.Ticker(ticker)
data = stock.history(period=period, interval=interval)
return data
def calculate_moving_average(data, window):
"""
Calculates the moving average for the given data.
Args:
data (pd.Series): Stock price data.
window (int): Window size for the moving average.
Returns:
pd.Series: Moving average data.
"""
return data.rolling(window=window).mean()
def implement_strategy(data, short_window, long_window):
"""
Implements a simple scalping strategy based on moving averages.
Args:
data (pd.DataFrame): Stock data.
short_window (int): Window size for the short moving average.
long_window (int): Window size for the long moving average.
Returns:
pd.DataFrame: DataFrame with trading signals and strategy returns.
"""
data['Short_MA'] = calculate_moving_average(data['Close'], short_window)
data['Long_MA'] = calculate_moving_average(data['Close'], long_window)
data['Signal'] = 0
data['Signal'][short_window:] = np.where(data['Short_MA'][short_window:] > data['Long_MA'][short_window:], 1, 0)
data['Position'] = data['Signal'].diff()
return data
def backtest_strategy(data, initial_capital=10000):
"""
Backtests the trading strategy.
Args:
data (pd.DataFrame): DataFrame with trading signals.
initial_capital (float): Initial capital for backtesting.
Returns:
float: Final portfolio value.
"""
data['Portfolio_Value'] = initial_capital
data['Position_Value'] = 0
for i in range(1, len(data)):
data['Position_Value'].iloc[i] = data['Position'].iloc[i] * data['Close'].iloc[i]
data['Portfolio_Value'].iloc[i] = data['Portfolio_Value'].iloc[i-1] + data['Position_Value'].iloc[i]
return data['Portfolio_Value'].iloc[-1]
def plot_data(data):
"""
Plots the stock data along with moving averages and signals.
Args:
data (pd.DataFrame): DataFrame with stock data and signals.
"""
plt.figure(figsize=(14,7))
plt.plot(data['Close'], label='Close Price')
plt.plot(data['Short_MA'], label='Short MA', alpha=0.7)
plt.plot(data['Long_MA'], label='Long MA', alpha=0.7)
plt.plot(data.loc[data['Position'] == 1].index, data['Short_MA'][data['Position'] == 1], '^', markersize=10, color='g', label='Buy Signal')
plt.plot(data.loc[data['Position'] == -1].index, data['Short_MA'][data['Position'] == -1], 'v', markersize=10, color='r', label='Sell Signal')
plt.title('Intraday Scalping Strategy')
plt.legend()
plt.show()
# Parameters
ticker = 'AAPL'
short_window = 5
long_window = 20
initial_capital = 10000
# Fetch stock data
data = get_stock_data(ticker)
# Implement strategy
data = implement_strategy(data, short_window, long_window)
# Backtest strategy
final_portfolio_value = backtest_strategy(data, initial_capital)
print(f"Final portfolio value: ${final_portfolio_value:.2f}")
# Plot data
plot_data(data)
```
### Explanation
1. **Fetching Stock Data**:
- The `get_stock_data` function uses `yfinance` to fetch intraday data for a specified ticker, period, and interval.
2. **Calculating Moving Averages**:
- The `calculate_moving_average` function calculates moving averages over a specified window.
3. **Implementing the Strategy**:
- The `implement_strategy` function uses short and long moving averages to generate buy and sell signals. A buy signal is generated when the short moving average crosses above the long moving average, and a sell signal is generated when it crosses below.
4. **Backtesting the Strategy**:
- The `backtest_strategy` function simulates trading using the generated signals and calculates the final portfolio value.
5. **Plotting Data**:
- The `plot_data` function visualizes the stock prices along with the moving averages and buy/sell signals.
### Note
This is a simple example and may not be profitable in real-world trading. For a robust intraday scalping strategy, consider incorporating more sophisticated techniques and risk management practices. Additionally, always test your strategies thoroughly before deploying them with real money.
No Comments have been Posted.