Update projects/forex_algo_trading.md
This commit is contained in:
@@ -55,55 +55,64 @@ swing_trading_project/
|
|||||||
```python
|
```python
|
||||||
import os
|
import os
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from oandapyV20 import API
|
from oandapyV20 import API # Import the Oanda API client
|
||||||
import oandapyV20.endpoints.instruments as instruments
|
import oandapyV20.endpoints.instruments as instruments
|
||||||
|
|
||||||
# Configuration
|
# Set your Oanda API credentials and configuration for data fetching
|
||||||
ACCOUNT_ID = 'your_account_id_here'
|
ACCOUNT_ID = 'your_account_id_here'
|
||||||
ACCESS_TOKEN = 'your_access_token_here'
|
ACCESS_TOKEN = 'your_access_token_here'
|
||||||
INSTRUMENTS = ['EUR_USD', 'USD_JPY', 'GBP_USD', 'AUD_USD', 'USD_CAD'] # Extendable to more pairs
|
# List of currency pairs to fetch. Add or remove pairs as needed.
|
||||||
GRANULARITY = 'H4' # Can be parameterized as needed
|
CURRENCY_PAIRS = ['EUR_USD', 'USD_JPY', 'GBP_USD', 'AUD_USD', 'USD_CAD']
|
||||||
DATA_DIR = 'data'
|
TIME_FRAME = 'H4' # 4-hour candles, change as per your analysis needs
|
||||||
|
DATA_DIRECTORY = 'data' # Directory where fetched data will be saved
|
||||||
|
|
||||||
def fetch_and_save_data(account_id, access_token, instruments, granularity, data_dir):
|
# Ensure the data directory exists, create it if it doesn't
|
||||||
"""Fetch historical forex data for specified instruments and save to CSV."""
|
if not os.path.exists(DATA_DIRECTORY):
|
||||||
client = API(access_token=access_token)
|
os.makedirs(DATA_DIRECTORY)
|
||||||
|
|
||||||
if not os.path.exists(data_dir):
|
def fetch_and_save_forex_data(account_id, access_token, currency_pairs, time_frame, data_dir):
|
||||||
os.makedirs(data_dir)
|
"""Fetch historical forex data for specified currency pairs and save it to CSV files."""
|
||||||
|
# Initialize the Oanda API client with your access token
|
||||||
|
api_client = API(access_token=access_token)
|
||||||
|
|
||||||
for instrument in instruments:
|
for pair in currency_pairs:
|
||||||
params = {
|
# Define the parameters for the data request: time frame and number of data points
|
||||||
"granularity": granularity,
|
request_params = {"granularity": time_frame, "count": 5000}
|
||||||
"count": 5000 # Adjust based on needs
|
|
||||||
}
|
|
||||||
|
|
||||||
data_request = instruments.InstrumentsCandles(instrument=instrument, params=params)
|
# Prepare the data request for fetching candle data for the current currency pair
|
||||||
data = client.request(data_request)
|
data_request = instruments.InstrumentsCandles(instrument=pair, params=request_params)
|
||||||
candles = data.get('candles', [])
|
# Fetch the data
|
||||||
|
response = api_client.request(data_request)
|
||||||
|
# Extract the candle data from the response
|
||||||
|
candle_data = response.get('candles', [])
|
||||||
|
|
||||||
if candles:
|
# If data was fetched, proceed to save it
|
||||||
df = pd.DataFrame([{
|
if candle_data:
|
||||||
|
# Convert the candle data into a pandas DataFrame
|
||||||
|
forex_data_df = pd.DataFrame([{
|
||||||
'Time': candle['time'],
|
'Time': candle['time'],
|
||||||
'Open': float(candle['mid']['o']),
|
'Open': float(candle['mid']['o']),
|
||||||
'High': float(candle['mid']['h']),
|
'High': float(candle['mid']['h']),
|
||||||
'Low': float(candle['mid']['l']),
|
'Low': float(candle['mid']['l']),
|
||||||
'Close': float(candle['mid']['c']),
|
'Close': float(candle['mid']['c']),
|
||||||
'Volume': candle['volume']
|
'Volume': candle['volume']
|
||||||
} for candle in candles])
|
} for candle in candle_data])
|
||||||
|
|
||||||
# Save to CSV
|
# Construct the filename for the CSV file
|
||||||
output_filename = f"{instrument.lower()}_data.csv"
|
csv_filename = f"{pair.lower()}_data.csv"
|
||||||
df.to_csv(os.path.join(data_dir, output_filename), index=False)
|
# Save the DataFrame to a CSV file in the specified data directory
|
||||||
print(f"Data saved for {instrument} to {output_filename}")
|
forex_data_df.to_csv(os.path.join(data_dir, csv_filename), index=False)
|
||||||
|
print(f"Data for {pair} saved to {csv_filename}")
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""Main function to orchestrate data fetching and saving."""
|
"""Orchestrates the data fetching and saving process."""
|
||||||
print("Fetching data for instruments...")
|
print("Starting data fetching process...")
|
||||||
fetch_and_save_data(ACCOUNT_ID, ACCESS_TOKEN, INSTRUMENTS, GRANULARITY, DATA_DIR)
|
# Call the function to fetch and save data for the configured currency pairs
|
||||||
print("Data fetching and saving complete.")
|
fetch_and_save_forex_data(ACCOUNT_ID, ACCESS_TOKEN, CURRENCY_PAIRS, TIME_FRAME, DATA_DIRECTORY)
|
||||||
|
print("Data fetching process completed.")
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
# Execute the script
|
||||||
main()
|
main()
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user