Assumption:
假设: 人来下单。对接行情,MACD线,BOLL线
Certainly! Let’s create a simple Python program to implement a basic trading strategy. We’ll use a simple moving average crossover strategy, which is a common and straightforward approach in quantitative trading. In this strategy, we’ll use two moving averages: a short-term moving average (e.g., 5 periods) and a long-term moving average (e.g., 20 periods). When the short-term moving average crosses above the long-term moving average, it’s a signal to buy. When it crosses below, it’s a signal to sell.
Here’s a simple implementation:
-
Install necessary libraries:
bash pip install pandas numpy
-
Create the trading strategy:
import pandas as pd
import numpy as np
# Sample data for demonstration (you should replace this with actual market data)
data = {
'timestamp': pd.date_range(start='2023-05-01', periods=100, freq='H'),
'close': np.random.randn(100).cumsum() + 3700 # Random walk around 3700
}
df = pd.DataFrame(data)
# Parameters
short_window = 5
long_window = 20
leverage = 10
trading_fee = 0.0008
# Calculate moving averages
df['short_mavg'] = df['close'].rolling(window=short_window).mean()
df['long_mavg'] = df['close'].rolling(window=long_window).mean()
# Generate signals
df['signal'] = 0
df['signal'][short_window:] = np.where(
df['short_mavg'][short_window:] > df['long_mavg'][short_window:], 1, 0)
df['position'] = df['signal'].diff()
# Function to execute trades
def execute_trades(df):
for i in range(len(df)):
if df['position'][i] == 1:
print(f"Buy at {df['close'][i]:.2f}")
elif df['position'][i] == -1:
print(f"Sell at {df['close'][i]:.2f}")
# Apply the trading strategy
execute_trades(df)
# Calculate performance (simple approach)
initial_balance = 10000
balance = initial_balance
position = 0
for i in range(len(df)):
if df['position'][i] == 1: # Buy
position = balance * leverage / df['close'][i]
balance -= balance * leverage * trading_fee
elif df['position'][i] == -1: # Sell
balance += position * df['close'][i]
balance -= position * df['close'][i] * trading_fee
position = 0
final_balance = balance + position * df['close'].iloc[-1]
print(f"Initial Balance: ${initial_balance:.2f}")
print(f"Final Balance: ${final_balance:.2f}")
print(f"Net Profit: ${final_balance - initial_balance:.2f}")
Explanation:
- Data Preparation:
- We use a sample dataset with random walk data around 3700. Replace this with actual market data.
- Parameters:
short_window
andlong_window
define the periods for the moving averages.leverage
is set to 10x.trading_fee
is 0.08% (0.0008 in decimal form).
- Moving Averages:
- We calculate the short-term and long-term moving averages.
- Signals:
- We generate buy (
1
) and sell (-1
) signals based on the crossover of the moving averages.
- We generate buy (
- Execute Trades:
- We print out buy and sell actions based on the signals.
- Performance Calculation:
- We simulate the balance changes based on the trades, taking into account the leverage and trading fees.
This is a basic implementation. In a real-world scenario, you would need to handle more complexities such as slippage, more advanced risk management, and integration with a trading API.