give me the proper code and use both clibraries to add two column to my csv file
one for talib bearish bullish candle_pattern
and one for pyTA candle_type
and save it as a new file
Assistant
To add two columns to an existing CSV file with one column containing TA-Lib bearish/bullish candlestick patterns and the other containing PyTechnicalAnalysis (pyTA) candle types, you would perform the following steps:
Read your existing CSV file into a pandas DataFrame.
Add a new column for each library's output by applying the corresponding functions to the price data columns.
Save the modified DataFrame as a new CSV file.
First, ensure you have the required libraries installed:
import pandas as pd
import talib
from PyTechnicalAnalysis import Candlestick
# Load your CSV file into a DataFrame
input_file_path = 'your_input_file.csv' # Replace with your CSV file path
output_file_path = 'your_output_file.csv' # Replace with desired output file path
df = pd.read_csv(input_file_path)
# Assuming your CSV has open, high, low, and close columns named 'Open', 'High', 'Low', 'Close'
opens = df['Open']
highs = df['High']
lows = df['Low']
closes = df['Close']
# Calculate candlestick patterns using TA-Lib
df['TA_Lib_Pattern'] = 'None'
for pattern_name in talib.get_function_groups()['Pattern Recognition']:
pattern_function = getattr(talib, pattern_name)
pattern_result = pattern_function(opens, highs, lows, closes)
# Since TA-Lib can return 100, 200, ... for bullish patterns or, -100, -200 for bearish patterns
# We map these to "Bullish" or "Bearish". Otherwise, if the result is 0, we keep "None"
df['TA_Lib_Pattern'] = df.apply(lambda row: pattern_name if row['TA_Lib_Pattern'] == 'None' and pattern_result[row.name] != 0 else row['TA_Lib_Pattern'], axis=1)
# Calculate candlestick types using PyTechnicalAnalysis
candlestick = Candlestick()
df['PyTA_Candle_Type'] = df.apply(lambda row: candlestick.candle_type(row['Open'], row['Close'], row['High'], row['Low']), axis=1)
# Save the modified DataFrame to a new CSV file
df.to_csv(output_file_path, index=False)
print(f'CSV file saved with additional columns as {output_file_path}')
Please replace 'your_input_file.csv' with the path to your input CSV file and 'your_output_file.csv' with the path where you'd like to save the output CSV file.
Remember to check the column names ('Open', 'High', 'Low', 'Close') of your input CSV file and adjust the code accordingly if they are different. This code also assumes that you would like to label exactly one pattern per row using TA-Lib functions; if a candle matches multiple patterns, the loop will overwrite them until it finds the last matching pattern. The PyTechnicalAnalysis library provides a single candle type per row by design.